Proprietà indicizzate C # Reflection
-
08-07-2019 - |
Domanda
Sto scrivendo un metodo Clone usando reflection. Come posso rilevare che una proprietà è una proprietà indicizzata usando la riflessione? Ad esempio:
public string[] Items
{
get;
set;
}
Il mio metodo finora:
public static T Clone<T>(T from, List<string> propertiesToIgnore) where T : new()
{
T to = new T();
Type myType = from.GetType();
PropertyInfo[] myProperties = myType.GetProperties();
for (int i = 0; i < myProperties.Length; i++)
{
if (myProperties[i].CanWrite && !propertiesToIgnore.Contains(myProperties[i].Name))
{
myProperties[i].SetValue(to,myProperties[i].GetValue(from,null),null);
}
}
return to;
}
Soluzione
if (propertyInfo.GetIndexParameters().Length > 0)
{
// Property is an indexer
}
Altri suggerimenti
Siamo spiacenti, ma
public string[] Items { get; set; }
non è non una proprietà indicizzata, è semplicemente un tipo di array! Tuttavia è il seguente:
public string this[int index]
{
get { ... }
set { ... }
}
Quello che vuoi è il metodo GetIndexParameters ()
. Se l'array che restituisce ha più di 0 elementi, significa che è una proprietà indicizzata.
Vedi la documentazione MSDN per ulteriori informazioni i dettagli.
Se si chiama property.GetValue (obj, null)
e la proprietà è indicizzata, si otterrà un'eccezione di mancata corrispondenza del conteggio dei parametri. Meglio verificare se la proprietà è indicizzata usando GetIndexParameters ()
e quindi decidere cosa fare.
Ecco del codice che ha funzionato per me:
foreach (PropertyInfo property in obj.GetType().GetProperties()) { object value = property.GetValue(obj, null); if (value is object[]) { .... } }
P.S. .GetIndexParameters (). Lunghezza > 0)
funziona per il caso descritto in questo articolo: http: // msdn.microsoft.com/en-us/library/b05d59ty.aspx
Quindi, se ti interessa la proprietà denominata Chars per un valore di tipo stringa, usalo, ma non funziona per la maggior parte degli array a cui ero interessato, incluso, ne sono abbastanza sicuro, un array di stringhe dalla domanda originale.
Puoi convertire l'indicizzatore in IEnumerable
public static IEnumerable<T> AsEnumerable<T>(this object o) where T : class {
var list = new List<T>();
System.Reflection.PropertyInfo indexerProperty = null;
foreach (System.Reflection.PropertyInfo pi in o.GetType().GetProperties()) {
if (pi.GetIndexParameters().Length > 0) {
indexerProperty = pi;
break;
}
}
if (indexerProperty.IsNotNull()) {
var len = o.GetPropertyValue<int>("Length");
for (int i = 0; i < len; i++) {
var item = indexerProperty.GetValue(o, new object[]{i});
if (item.IsNotNull()) {
var itemObject = item as T;
if (itemObject.IsNotNull()) {
list.Add(itemObject);
}
}
}
}
return list;
}
public static bool IsNotNull(this object o) {
return o != null;
}
public static T GetPropertyValue<T>(this object source, string property) {
if (source == null)
throw new ArgumentNullException("source");
var sourceType = source.GetType();
var sourceProperties = sourceType.GetProperties();
var properties = sourceProperties
.Where(s => s.Name.Equals(property));
if (properties.Count() == 0) {
sourceProperties = sourceType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic);
properties = sourceProperties.Where(s => s.Name.Equals(property));
}
if (properties.Count() > 0) {
var propertyValue = properties
.Select(s => s.GetValue(source, null))
.FirstOrDefault();
return propertyValue != null ? (T)propertyValue : default(T);
}
return default(T);
}