Ответ 1
if (propertyInfo.GetIndexParameters().Length > 0)
{
// Property is an indexer
}
Я пишу метод Clone с использованием отражения. Как определить, что свойство является индексированным свойством с использованием отражения? Например:
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 { ... }
}
Вы хотите использовать метод GetIndexParameters()
. Если массив, который он возвращает, имеет более чем 0 элементов, что означает его индексированное свойство.
Подробнее см. документацию MSDN.
Если вы вызываете property.GetValue(obj,null)
, а свойство IS проиндексировано, вы получите исключение несоответствия счетчика параметров. Лучше проверить, индексируется ли свойство с помощью GetIndexParameters()
, а затем решить, что делать.
Вот какой код работал у меня:
foreach (PropertyInfo property in obj.GetType().GetProperties()) { object value = property.GetValue(obj, null); if (value is object[]) { .... } }
P.S. .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);
}