Dan*_*nor 22 c# reflection explicit-interface
更具体地说,如果我有:
public class TempClass : TempInterface
{
int TempInterface.TempProperty
{
get;
set;
}
int TempInterface.TempProperty2
{
get;
set;
}
public int TempProperty
{
get;
set;
}
}
public interface TempInterface
{
int TempProperty
{
get;
set;
}
int TempProperty2
{
get;
set;
}
}
Run Code Online (Sandbox Code Playgroud)
如何使用反射来获取显式实现TempInterface的属性的所有propertyInfos?
谢谢.
小智 22
我认为您正在寻找的类是System.Reflection.InterfaceMapping.
Type ifaceType = typeof(TempInterface);
Type tempType = typeof(TempClass);
InterfaceMapping map = tempType.GetInterfaceMap(ifaceType);
for (int i = 0; i < map.InterfaceMethods.Length; i++)
{
MethodInfo ifaceMethod = map.InterfaceMethods[i];
MethodInfo targetMethod = map.TargetMethods[i];
Debug.WriteLine(String.Format("{0} maps to {1}", ifaceMethod, targetMethod));
}
Run Code Online (Sandbox Code Playgroud)
显式实现的接口属性的属性 getter 和 setter 有一个不寻常的属性。它的 IsFinal 属性为 True,即使它不是密封类的成员。尝试这段代码来验证我的断言:
foreach (AssemblyName name in Assembly.GetEntryAssembly().GetReferencedAssemblies()) {
Assembly asm = Assembly.Load(name);
foreach (Type t in asm.GetTypes()) {
if (t.IsAbstract) continue;
foreach (MethodInfo mi in t.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)) {
int dot = mi.Name.LastIndexOf('.');
string s = mi.Name.Substring(dot + 1);
if (!s.StartsWith("get_") && !s.StartsWith("set_")) continue;
if (mi.IsFinal)
Console.WriteLine(mi.Name);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我不得不修改雅各布·卡彭特的答案,但效果很好。nobugz 也可以,但 Jacobs 更紧凑。
var explicitProperties =
from method in typeof(TempClass).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
where method.IsFinal && method.IsPrivate
select method;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11338 次 |
最近记录: |