C#反射索引属性

Gre*_*zer 23 c# reflection clone

我正在使用反射编写克隆方法.如何使用反射检测属性是索引属性?例如:

public string[] Items
{
   get;
   set;
}
Run Code Online (Sandbox Code Playgroud)

我的方法到目前为止:

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;
}
Run Code Online (Sandbox Code Playgroud)

Fly*_*wat 48

if (propertyInfo.GetIndexParameters().Length > 0)
{
    // Property is an indexer
}
Run Code Online (Sandbox Code Playgroud)


小智 20

对不起,可是

public string[] Items { get; set; }
Run Code Online (Sandbox Code Playgroud)

不是索引属性,它只是一个数组类型的!但是以下是:

public string this[int index]
{
    get { ... }
    set { ... }
}
Run Code Online (Sandbox Code Playgroud)

  • 好的,但是如何通过反射找到它呢? (3认同)

Jer*_*ine 9

你想要的是GetIndexParameters()方法.如果它返回的数组有多于0个项,则表示它是一个索引属性.

有关更多详细信息,请参阅MSDN文档.