Come posso usare la riflessione per ottenere proprietà che implementano esplicitamente un'interfaccia?
-
07-07-2019 - |
Domanda
Più specificamente, se ho:
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;
}
}
Come posso usare la reflection per ottenere tutte le proprietàInfos per le proprietà che implementano esplicitamente TempInterface?
Grazie.
Soluzione 5
Ho dovuto modificare la risposta di Jacob Carpenter, ma funziona bene. Nobugz funziona anche, ma Jacobs è più compatto.
var explicitProperties =
from method in typeof(TempClass).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
where method.IsFinal && method.IsPrivate
select method;
Altri suggerimenti
Penso che la classe che stai cercando sia 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));
}
Il getter di proprietà e il setter di una proprietà di interfaccia esplicitamente implementata hanno un attributo insolito. La proprietà IsFinal è True, anche quando non è un membro di una classe sigillata. Prova questo codice per verificare la mia affermazione:
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);
}
}
}
Ecco una soluzione modificata basata sull'implementazione fornita in questo post sul blog :
var explicitProperties =
from prop in typeof(TempClass).GetProperties(
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)
let getAccessor = prop.GetGetMethod(true)
where getAccessor.IsFinal && getAccessor.IsPrivate
select prop;
foreach (var p in explicitProperties)
Console.WriteLine(p.Name);
Basandosi su risposta di MrKurt :
var targetMethods =
from iface in typeof(TempClass).GetInterfaces()
from method in typeof(TempClass).GetInterfaceMap(iface).TargetMethods
select method;
var explicitProps =
from prop in typeof(TempClass).GetProperties(BindingFlags.Instance |
BindingFlags.NonPublic)
where targetMethods.Contains(prop.GetGetMethod(true)) ||
targetMethods.Contains(prop.GetSetMethod(true))
select prop;
È eccessivamente complesso. Devi riflettere sui metodi / proprietà del tipo di interfaccia, vedere se esistono nel tuo tipo di classe e confrontarli per vedere se sono gli stessi " stesso " quando esistono.
Se c'è qualcosa nell'interfaccia ma non il tipo che stai testando, si tratta di un'implementazione esplicita. Se è in entrambi, ma diverso tra i due, è un'interfaccia esplicita.
Nel codice di Jacob manca un filtro:
var props = typeof(TempClass).GetInterfaces().Where(i => i.Name=="TempInterface").SelectMany(i => i.GetProperties());
foreach (var prop in props)
Console.WriteLine(prop);
Sembra un po 'doloroso senza una ragione apparente!
La mia soluzione è per il caso in cui conosci il nome della proprietà che stai cercando ed è piuttosto semplice.
Ho una lezione per rendere un po 'più semplice la riflessione e ho dovuto aggiungere questo caso a:
public class PropertyInfoWrapper
{
private readonly object _parent;
private readonly PropertyInfo _property;
public PropertyInfoWrapper(object parent, string propertyToChange)
{
var type = parent.GetType();
var privateProperties= type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);
var property = type.GetProperty(propertyToChange) ??
privateProperties.FirstOrDefault(p => UnQualifiedNameFor(p) == propertyName);
if (property == null)
throw new Exception(string.Format("cant find property |{0}|", propertyToChange));
_parent = parent;
_property = property;
}
private static string UnQualifiedNameFor(PropertyInfo p)
{
return p.Name.Split('.').Last();
}
public object Value
{
get { return _property.GetValue(_parent, null); }
set { _property.SetValue(_parent, value, null); }
}
}
Non puoi semplicemente fare == sul nome perché le proprietà implementate esplicitamente hanno nomi completi.
GetProperties ha bisogno di entrambi i flag di ricerca per accedere alle proprietà private.
Una semplice classe di supporto che potrebbe aiutare:
public class InterfacesPropertiesMap
{
private readonly Dictionary<Type, PropertyInfo[]> map;
public InterfacesPropertiesMap(Type type)
{
this.Interfaces = type.GetInterfaces();
var properties = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
this.map = new Dictionary<Type, PropertyInfo[]>(this.Interfaces.Length);
foreach (var intr in this.Interfaces)
{
var interfaceMap = type.GetInterfaceMap(intr);
this.map.Add(intr, properties.Where(p => interfaceMap.TargetMethods
.Any(t => t == p.GetGetMethod(true) ||
t == p.GetSetMethod(true)))
.Distinct().ToArray());
}
}
public Type[] Interfaces { get; private set; }
public PropertyInfo[] this[Type interfaceType]
{
get { return this.map[interfaceType]; }
}
}
Otterrai le proprietà per ogni interfaccia, anche esplicitamente implementata.