[英]How to Get the Value of a List Type Property using propertyInfo
private static void Getproperties(Object Model) {
Type objType = Model.GetType();
PropertyInfo[] properties = objType.GetProperties();
foreach (PropertyInfo property in properties)
{
object propValue;
//Checking if property is indexed
if(property.GetIndexParameters().Length ==0)
propValue = property.GetValue(Model,null);
else
{
// want to retrieve collection stored in property index not passing 0 index returning element at 0 location ,how can i get whole list
propValue = property.GetValue(objectModel,new Object[]{0});
}
var elems = propValue as IList;
.... }
How can i get the Property Value of List Type, my property in the Model is a List Type for Example my Model contains a List Property 如何获取列表类型的属性值,我在模型中的属性是示例的列表类型,我的模型包含列表属性
List<User>
wants to create a Filter and add to action on which i can check for potential Xss Attack ,whether model contains any such attack 想要创建一个过滤器并添加到行动,我可以检查潜在的Xss攻击,模型是否包含任何此类攻击
You don't really need this overload with second parameter. 你不需要第二个参数的这个重载。 What you really need is to cast
object
returned by .GetValue()
method back to type List<T>
. 你真正需要的是将
.GetValue()
方法返回的object
.GetValue()
回List<T>
类型。 Example : 示例:
class MyClass
{
public List<int> MyProperty { get { return new List<int>() { 3, 4, 5, 6 }; } }
}
class Program
{
static void Main()
{
MyClass instance = new MyClass();
PropertyInfo info = instance.GetType().GetProperty("MyProperty");
List<int> another = info.GetValue(instance) as List<int>;
for (int i = 0; i < another.Count; i++)
{
Console.Write(another[i] + " ");
}
}
}
Output : 3 4 5 6
输出:
3 4 5 6
Check this one. 检查一下。
List<string> sbColors = new List<string>();
Type colorType = typeof(System.Drawing.Color);
PropertyInfo[] propInfoList = colorType.GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public);
foreach (PropertyInfo c in propInfoList)
{
sbColors.Add(c.Name);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.