【发布时间】:2013-07-27 11:02:06
【问题描述】:
我上了这门课
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] 的东西来获取 Caller 的类所有者的类型吗?
【问题讨论】:
-
CompilerServices提供的信息在我看来太少,无法从调用方法中获取类型。但是您可以尝试使用[CallerFilePath]访问文件,然后转到[CallerLineNumber]给出的行并从那里找出类名。然后在调用程序集上使用反射从您获得的名称中获取Type。或者.. 考虑到可怕的性能和安全问题.. 提供Type作为参数是最简单的选择。 -
"提供类型作为参数是最简单的选择" 只是这是我不想要的,如果我有一个有 20 个方法的类需要为每个方法提供类名,如果需要重构这将是一个头疼的问题。 Tks 我正在考虑这种方式,但真的不喜欢它。
-
遍历堆栈以确定调用者类型非常昂贵,为什么需要这个?是否有其他方法可以获得您想要的相同结果?
-
@Jay 在我的应用程序中有一些受监督的东西,我需要检查一个类的一个方法是否被标记为受监督的数据库。
-
所以您只希望某些类型调用这些方法?如果你对调用方法有任何控制权,你应该从那里开始,而不是在调用之后分支逻辑。
标签: c#