我正在使用反射编写克隆方法。如何使用反射检测属性是否为索引属性?例如:
public string[] Items
{
get;
set;
}
到目前为止我的方法:
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;
}
if (propertyInfo.GetIndexParameters().Length > 0)
{
// Property is an indexer
}
您发布的示例不是索引属性,它是具有数组类型的普通属性:
public string[] Items { get; set; }
索引属性看起来像这样:
public string this[int index]
{
get { ... }
set { ... }
}
如果您调用
property.GetValue(obj,null)
,并且属性被索引,那么您将得到一个参数计数不匹配异常。最好使用 GetIndexParameters()
检查属性是否被索引,然后决定要做什么。
这是一些对我有用的代码:
foreach(obj.GetType().GetProperties() 中的 PropertyInfo 属性) { 对象值 = property.GetValue(obj, null); 如果(值为对象[]) { .... } }
附言
.GetIndexParameters().Length > 0)
适用于本文所述的案例:http://msdn.microsoft.com/en-us/library/b05d59ty.aspx
因此,如果您关心字符串类型值的名为 Chars 的属性,请使用它,但它不适用于我感兴趣的大多数数组,包括,我很确定,来自原始问题的字符串数组。
您可以将索引器转换为 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);
}