c# - 如何获取 CallerMember 的类型名称

标签 c#

我上了这门课

public class fooBase
{
    public List<MethodsWithCustAttribute> MethodsList;
    public bool fooMethod([CallerMemberName]string membername =""))
    {
        //This returns a value depending of type and method 
    } 
    public void GetMethods()
    {
        // Here populate MethodsList using reflection
    }
}

还有这个属性类

// This attribute get from a database some things, then fooMethod check this attribute members 
public class CustomAttribute
{
    public string fullMethodPath;
    public bool someThing ; 
    public bool CustomAttribute([CallerMemberName]string membername ="")
    {
        fullMethodPath = **DerivedType** + membername 
        //  I need here to get the type of membername parent. 
        //  Here I want to get CustClass, not fooBase

    }
}

然后我有这个

public class CustClass : fooBase
{
     [CustomAttribute()]
     public string method1()
     {
         if (fooMethod())
         {
             ....
         }
     }
}

我需要 CallerMember 的类型名称,是否有类似 [CallerMemberName] 的东西来获取调用者的类所有者的类型?

最佳答案

这并非万无一失,但 .NET 的惯例是每个文件有一个类型,并将文件命名为与该类型相同的名称。我们的工具也倾向于强制执行此约定,即 Resharper 和 Visual Studio。

因此从文件路径推断类型名应该是合理的。

public class MyClass
{
  public void MyMethod([CallerFilePath]string callerFilePath = null, [CallerMemberName]string callerMemberName = null)
  {
    var callerTypeName = Path.GetFileNameWithoutExtension(callerFilePath);
    Console.WriteLine(callerTypeName);
    Console.WriteLine(callerMemberName);
  }
}

关于c# - 如何获取 CallerMember 的类型名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17893827/

相关文章:

c# - 什么是NullReferenceException,如何解决?

c# - 替换参数以指向 lambda 表达式中的嵌套参数

c# - 检查用户输入是真还是假

c# - C# 属性可以访问目标类吗?

c# - 从 ASP.Net Web Api 获取数据时获取 403 状态

c# - 为什么我不能将此接口(interface)转换为具体类?

c# - 使用 $expand 时的 Web API OData 媒体类型格式化程序

c# - TPL 的性能计数器?

c# - 让 Lucene 在术语中包含空格以进行精确匹配

c# - 是否有更通用的方法来执行此类行为?