如何通过C#中的类型查找.cs文件的路径 [英] How to find path to .cs file by its type in C#

查看:277
本文介绍了如何通过C#中的类型查找.cs文件的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何按类型查找.cs文件的路径?

How to find path to .cs file by its type?

函数原型:

string FindPath(Type);

返回类似 C:\Projects\ ..... \MyClass.cs的

Returns something like "C:\Projects\.....\MyClass.cs"

推荐答案

在.Net 4.5中,您可以使用 CallerFilePath 反射属性(来自MSDN):

In .Net 4.5 you can use the CallerFilePath reflection attribute (from MSDN):

// using System.Runtime.CompilerServices 
// using System.Diagnostics; 

public void DoProcessing()
{
    TraceMessage("Something happened.");
}

public void TraceMessage(string message,
        [CallerMemberName] string memberName = "",
        [CallerFilePath] string sourceFilePath = "",
        [CallerLineNumber] int sourceLineNumber = 0)
{
    Trace.WriteLine("message: " + message);
    Trace.WriteLine("member name: " + memberName);
    Trace.WriteLine("source file path: " + sourceFilePath);
    Trace.WriteLine("source line number: " + sourceLineNumber);
}

// Sample Output: 
//  message: Something happened. 
//  member name: DoProcessing 
//  source file path: c:\Users\username\Documents\Visual Studio 2012\Projects\CallerInfoCS\CallerInfoCS\Form1.cs 
//  source line number: 31

请参阅: http://msdn.microsoft.com/zh-cn/ library / system.runtime.compilerservices.callerfilepathattribute(v = vs.110).aspx

这篇关于如何通过C#中的类型查找.cs文件的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆