反映字符串时抛出的参数计数不匹配

P.B*_*key 3 c# reflection

我有一个适用于我的大多数自定义类型的通用方法.今天我正在建立单元测试.扩展名失败string.string出现两个公共实例属性,LengthChars.当我称之为GetValue炸弹"参数计数不匹配"时.

我没有任何需要允许字符串.我可以为我的通用添加一个足以解决问题的约束吗?

代码段

public static DataTable ToDataTable<T>(this List<T> items){...

    //List<T> generally works...just found it failing out with string
    List<string> items = new List<string> { "cookie", "apple", "whatever" };
    System.Reflection.PropertyInfo[] props = typeof(string).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

    foreach (var item in items)
    {
        var values = new object[props.Length];
        for (var i = 0; i < props.Length; i++)
        {
            values[i] = props[i].GetValue(item, null);
        }
    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 9

Chars是C#术语中的索引器 - 但是.NET/CLR术语中的"具有索引参数的属性"...因此您只能通过指定参数来获取值.所以在这种情况下,它代表了这里使用的索引器:

char c = text[3];
Run Code Online (Sandbox Code Playgroud)

Dictionary<TKey, TValue>索引器中将是你得到的方式dictionary[key].

如果您只想要"普通"属性,请按PropertyInfo.GetIndexParameters()返回空数组的属性列表过滤属性列表.