我上了这门课
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/