我们在学习函数调用时,都知道每个函数都拥有自己的栈空间。一个函数被调用时,就创建一个新的栈空间。那么通过函数的嵌套调用最后就形成了一个函数调用堆栈。在c#中,使用StackTrace记录这个堆栈。你可以在程序运行过程中使用StackTrace得到当前堆栈的信息。

class Program
    {
        static void Main(string[] args)
        {
            Program a = new Program();
            a.FuncA();
            Console.ReadLine();
        }
        int FuncA()
        {
            FuncB();
            return ;
        }

        private void FuncB()
        {
            MethodInfo method0 = (MethodInfo)(new StackTrace().GetFrame().GetMethod());
            MethodInfo method1 = (MethodInfo)(new StackTrace().GetFrame().GetMethod());
            MethodInfo method2 = (MethodInfo)(new StackTrace().GetFrame().GetMethod());
            
            Console.WriteLine("Current Method is : {0}",method0.Name);
            Console.WriteLine("Parent Method is : {0}", method1.Name);
            Console.WriteLine("GrandParent Method is : {0}", method2.Name);
        }
    }

程序的输出结果是:
Current Method is : FuncB
Parent Method is : FuncA
GrandParent Method is : Main

其中调用GetFrame得到栈空间,参数index 表示栈空间的级别,0表示当前栈空间,1表示上一级的栈空间,依次类推。
       除了可以获取方法信息外,还可以调用StackFrame类的成员函数,在运行时得到代码的文件信息及行号和列号等。详情可以参考msdn上的一个example

msdn example
// Display the stack frame properties.
StackFrame sf = st.GetFrame(i);
Console.WriteLine(" File: {0}", sf.GetFileName());
Console.WriteLine(" Line Number: {0}", 
   sf.GetFileLineNumber());
// Note that the column number defaults to zero
// when not initialized.
Console.WriteLine(" Column Number: {0}", 
   sf.GetFileColumnNumber());
if (sf.GetILOffset() != StackFrame.OFFSET_UNKNOWN)
{
   Console.WriteLine(" Intermediate Language Offset: {0}", 
      sf.GetILOffset());
}
if (sf.GetNativeOffset() != StackFrame.OFFSET_UNKNOWN)
{
   Console.WriteLine(" Native Offset: {0}", 
      sf.GetNativeOffset());
}

在dudu的文章Attribute在.NET编程中的应用(四)一文中,就是通过StackTrace得到了其上一级的函数信息,即AddCustomer的信息,来进一步创建SqlParameter 的。详情请参见其文章。

为程序员打杂的站长

随笔-1352  文章-308  评论-27520 

Attribute在.NET编程中的应用(四)

 

SqlCommandGenerator类的设计

SqlCommandGEnerator类的设计思路就是通过反射得到方法的参数,使用被SqlCommandParameterAttribute标记的参数来装配一个Command实例。

引用的命名空间:

//SqlCommandGenerator.cs

using System;
using System.Reflection;
using System.Data;
using System.Data.SqlClient;
using Debug = System.Diagnostics.Debug;
using StackTrace = System.Diagnostics.StackTrace;

类代码:

namespace DataAccess
{
public sealed class SqlCommandGenerator
{
//私有构造器,不允许使用无参数的构造器构造一个实例
private SqlCommandGenerator()
{
throw new NotSupportedException();
} //静态只读字段,定义用于返回值的参数名称
public static readonly string ReturnValueParameterName = "RETURN_VALUE";
//静态只读字段,用于不带参数的存储过程
public static readonly object[] NoValues = new object[] {}; public static SqlCommand GenerateCommand(SqlConnection connection,
MethodInfo method, object[] values)
{
//如果没有指定方法名称,从堆栈帧得到方法名称
if (method == null)
method = (MethodInfo) (new StackTrace().GetFrame(1).GetMethod()); // 获取方法传进来的SqlCommandMethodAttribute
// 为了使用该方法来生成一个Command对象,要求有这个Attribute。
SqlCommandMethodAttribute commandAttribute =
(SqlCommandMethodAttribute) Attribute.GetCustomAttribute(method, typeof(SqlCommandMethodAttribute)); Debug.Assert(commandAttribute != null);
Debug.Assert(commandAttribute.CommandType == CommandType.StoredProcedure ||
commandAttribute.CommandType == CommandType.Text); // 创建一个SqlCommand对象,同时通过指定的attribute对它进行配置。
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = commandAttribute.CommandType; // 获取command的文本,如果没有指定,那么使用方法的名称作为存储过程名称
if (commandAttribute.CommandText.Length == 0)
{
Debug.Assert(commandAttribute.CommandType == CommandType.StoredProcedure);
command.CommandText = method.Name;
}
else
{
command.CommandText = commandAttribute.CommandText;
} // 调用GeneratorCommandParameters方法,生成command参数,同时添加一个返回值参数
GenerateCommandParameters(command, method, values);
command.Parameters.Add(ReturnValueParameterName, SqlDbType.Int).Direction
=ParameterDirection.ReturnValue; return command;
} private static void GenerateCommandParameters(
SqlCommand command, MethodInfo method, object[] values)
{ // 得到所有的参数,通过循环一一进行处理。 ParameterInfo[] methodParameters = method.GetParameters();
int paramIndex = 0; foreach (ParameterInfo paramInfo in methodParameters)
{
// 忽略掉参数被标记为[NonCommandParameter ]的参数 if (Attribute.IsDefined(paramInfo, typeof(NonCommandParameterAttribute)))
continue; // 获取参数的SqlParameter attribute,如果没有指定,那么就创建一个并使用它的缺省设置。
SqlParameterAttribute paramAttribute = (SqlParameterAttribute) Attribute.GetCustomAttribute(
paramInfo, typeof(SqlParameterAttribute)); if (paramAttribute == null)
paramAttribute = new SqlParameterAttribute(); //使用attribute的设置来配置一个参数对象。使用那些已经定义的参数值。如果没有定义,那么就从方法
// 的参数来推断它的参数值。
SqlParameter sqlParameter = new SqlParameter();
if (paramAttribute.IsNameDefined)
sqlParameter.ParameterName = paramAttribute.Name;
else
sqlParameter.ParameterName = paramInfo.Name; if (!sqlParameter.ParameterName.StartsWith("@"))
sqlParameter.ParameterName = "@" + sqlParameter.ParameterName; if (paramAttribute.IsTypeDefined)
sqlParameter.SqlDbType = paramAttribute.SqlDbType; if (paramAttribute.IsSizeDefined)
sqlParameter.Size = paramAttribute.Size; if (paramAttribute.IsScaleDefined)
sqlParameter.Scale = paramAttribute.Scale; if (paramAttribute.IsPrecisionDefined)
sqlParameter.Precision = paramAttribute.Precision; if (paramAttribute.IsDirectionDefined)
{
sqlParameter.Direction = paramAttribute.Direction;
}
else
{
if (paramInfo.ParameterType.IsByRef)
{
sqlParameter.Direction = paramInfo.IsOut ?
ParameterDirection.Output :
ParameterDirection.InputOutput;
}
else
{
sqlParameter.Direction = ParameterDirection.Input;
}
} // 检测是否提供的足够的参数对象值
Debug.Assert(paramIndex < values.Length); //把相应的对象值赋于参数。
sqlParameter.Value = values[paramIndex];
command.Parameters.Add(sqlParameter); paramIndex++;
} //检测是否有多余的参数对象值
Debug.Assert(paramIndex == values.Length);
}
}
}

必要的工作终于完成了。SqlCommandGenerator中的代码都加上了注释,所以并不难读懂。下面我们进入最后的一步,那就是使用新的方法来实现上一节我们一开始显示个那个AddCustomer的方法。

重构新的AddCustomer代码:

[ SqlCommandMethod(CommandType.StoredProcedure) ]
public void AddCustomer( [NonCommandParameter] SqlConnection connection,
[SqlParameter(50)] string customerName,
[SqlParameter(20)] string country,
[SqlParameter(20)] string province,
[SqlParameter(20)] string city,
[SqlParameter(60)] string address,
[SqlParameter(16)] string telephone,
out int customerId )
{
customerId=0; //需要初始化输出参数
//调用Command生成器生成SqlCommand实例
SqlCommand command = SqlCommandGenerator.GenerateCommand( connection, null, new object[]
{customerName,country,province,city,address,telephone,customerId } ); connection.Open();
command.ExecuteNonQuery();
connection.Close(); //必须明确返回输出参数的值
customerId=(int)command.Parameters["@CustomerId"].Value;
}

代码中必须注意的就是out参数,需要事先进行初始化,并在Command执行操作以后,把参数值传回给它。受益于Attribute,使我们摆脱了那种编写大量枯燥代码编程生涯。 我们甚至还可以使用Sql存储过程来编写生成整个方法的代码,如果那样做的话,可就大大节省了你的时间了,上一节和这一节中所示的代码,你可以把它们单独编译成一个组件,这样就可以在你的项目中不断的重用它们了。从下一节开始,我们将更深层次的介绍Attribute的应用,请继续关注。(待续)

原文: http://www.csdn.net/Develop/Read_Article.asp?Id=19591

浅析StackTrace【转】的更多相关文章

  1. 浅析StackTrace

    我们在学习函数调用时,都知道每个函数都拥有自己的栈空间.一个函数被调用时,就创建一个新的栈空间.那么通过函数的嵌套调用最后就形成了一个函数调用堆栈.在c#中,使用StackTrace记录这个堆栈.你可 ...

  2. .NET 中获取调用方法名

    在写记录日志功能时,需要记录日志调用方所在的模块名.命名空间名.类名以及方法名,想到使用的是反射(涉及到反射请注意性能),但具体是哪一块儿还不了解,于是搜索,整理如下: 需要添加相应的命名空间: us ...

  3. C#获取当前堆栈的各调用方法列表

    在使用.NET编写的代码在debug时很容易进行排查和定位问题,一旦项目上线并出现问题的话那么只能依靠系统日志来进行问题排查和定位,但当项目复杂时,即各种方法间相互调用将导致要获取具体的出错方法或调用 ...

  4. C#获取堆栈信息,输出文件名、行号、函数名、列号等

    命名空间:System.Diagnostics 得到相关信息: StackTrace st = new StackTrace(new StackFrame(true));StackFrame sf = ...

  5. 浅析DispatchProxy动态代理AOP

    浅析DispatchProxy动态代理AOP(代码源码) 最近学习了一段时间Java,了解到Java实现动态代理AOP主要分为两种方式JDK.CGLIB,我之前使用NET实现AOP切面编程,会用Fil ...

  6. SQL Server on Linux 理由浅析

    SQL Server on Linux 理由浅析 今天的爆炸性新闻<SQL Server on Linux>基本上在各大科技媒体上刷屏了 大家看到这个新闻都觉得非常震精,而美股,今天微软开 ...

  7. 【深入浅出jQuery】源码浅析--整体架构

    最近一直在研读 jQuery 源码,初看源码一头雾水毫无头绪,真正静下心来细看写的真是精妙,让你感叹代码之美. 其结构明晰,高内聚.低耦合,兼具优秀的性能与便利的扩展性,在浏览器的兼容性(功能缺陷.渐 ...

  8. 高性能IO模型浅析

    高性能IO模型浅析 服务器端编程经常需要构造高性能的IO模型,常见的IO模型有四种: (1)同步阻塞IO(Blocking IO):即传统的IO模型. (2)同步非阻塞IO(Non-blocking  ...

  9. netty5 HTTP协议栈浅析与实践

      一.说在前面的话 前段时间,工作上需要做一个针对视频质量的统计分析系统,各端(PC端.移动端和 WEB端)将视频质量数据放在一个 HTTP 请求中上报到服务器,服务器对数据进行解析.分拣后从不同的 ...

随机推荐

  1. ALSA音频工具amixer,aplay,arecord

    ALSA音频工具编译安装 ========================================================================1.官网http://www. ...

  2. Unity 2DSprite

    Unity官方意识到在4.3版本之前,并没有自带的支持2D游戏工具,商店里面有很多有名2D插件Uni2D,2DToolkit,在4.3版本之后就出现UISprite精灵来支持2D游戏开发,我用这个很多 ...

  3. 带你走近AngularJS - 创建自己定义指令

    带你走近AngularJS系列: 带你走近AngularJS - 基本功能介绍 带你走近AngularJS - 体验指令实例 带你走近AngularJS - 创建自己定义指令 ------------ ...

  4. poj1664 放苹果(递归)

    转载请注明出处:http://blog.csdn.net/u012860063?viewmode=contents 题目链接:http://poj.org/problem?id=1664 ------ ...

  5. 这个更新需要花去 50.6 M 磁盘上总计 /boot 的空间。请在 7737k 磁盘上留出 /boot 空间。清空您的回收站和临时文件,用“sudo apt-get clean

    系统升级会下载多余的内核,删除即可. 1.命令:dpkg --get-selections|grep linux             //带image的为系统内核 2.命令:   uname -a ...

  6. Java - 反射机制(Reflection)

    Java - 反射机制(Reflection)     > Reflection 是被视为 动态语言的关键,反射机制允许程序在执行期借助于 Reflection API 取得任何类的       ...

  7. android——拍照,相册图片剪切其实就这么简单

    接触android这么久了.还没有真正的浩浩看看android拍照,相册图片剪切到底是怎么回事,每次都是从别人的代码一扣,就过来了.其实,谷歌提供的API已经很强大.只需要用的好,就那么几句就可以搞定 ...

  8. 嵌套iframe中的HTML的文档解析类型

    问题:页面整个刷新时,IE11输入框显示的宽度和高度正常,对页面中的iframe部分刷新时,IE11输入框的宽度和高度就变小了. 原因:网页的头部定义了文档类型<!DOCTYPE html> ...

  9. Android Geocoder(位置解析)

    Android中提供GPS定位服务,同时开发者可以对获得的位置信息进行解析,可以获得位置的详细信息. 1.gps定位 在Eclipse中建立android应用程序.android sdk中提供了loc ...

  10. RFC端口号定义

    RFC关于计算机端口号定义 http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers. ...