且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用反射设置索引属性的值

更新时间:2023-02-09 15:47:17

假设您在 UserProfile 上只有一个索引器:

Assuming you only have one indexer on UserProfile:

PropertyInfo indexProperty = typeof(UserProfile)
    .GetProperties()
    .Single(p => p.GetIndexParameters().Length == 1 && p.GetIndexParameters()[0].ParameterType == typeof(string));

您现在可以获取索引器的值并设置其 Value 属性:

You can now get the value for the indexer and set its Value property:

object collection = indexProperty.GetValue(userProfile, new object[] { "PictureUrl" });

PropertyInfo valueProperty = collection.GetType().GetProperty("Value");
valueProperty.SetValue(collection, userPictureUrl, null);

如果您有多个匹配的索引属性,您可以通过以下方式找到它:

If you have more than one matching index property you can find it with:

PropertyInfo indexProperty = (from p in t.GetProperties()
                              let indexParams = p.GetIndexParameters()
                              where indexParams.Length == 1 && indexParams[0].ParameterType == typeof(string)
                              select p).Single();