C#检查泛型类型是否具有字符串属性并分配给它

时间:2016-03-25 18:31:43

标签: c# generics reflection

我们说,我有一个班级。

class A 
{
  string X {get; set;}
  string Y {get; set;}
}

并且在某些方法中我想问一下,如果泛型类(在我的情况下为A)具有by string指定的参数,如果是,则为其赋值;

class CreateGenerics<T> where T:new()
{
  public List<T> create(string attr, string[] attrValues) 
  {
    //I want to check if T has attribute attr (let's say "X")

    List<T> ret = new List<T>();
    foreach(string value in attrValues) {
      T t = new T();
      //set 'attr' attribute of T to value of 'value'
      ret.Add(t);
    }
    return ret;
  }
}

3 个答案:

答案 0 :(得分:1)

首先,您谈论的是属性而非属性。

您可以使用反射和泛型,例如在这种情况下,我正在检查类A上是否存在属性名称X:

public static List<T> Create<T>(string attr, string[] attrValues) where T: new()
{
   //I want to check if T has attribute attr (let's say "X")

   List<T> ret = new List<T>();
   foreach (string value in attrValues)
   {
      T t = new T();

      foreach (var property in typeof(T).GetProperties())
      {
         if (property.Name == attr) // setting value for x
         {
             property.SetValue(t, value);
         }
      }
       ret.Add(t);
   }
   return ret;
}
你可以这样称呼它:

var result = Create<A>("X",new string[]{"attrValues"});

假设您展示了您的课程,所有属性都是字符串

答案 1 :(得分:1)

你可以做这样的事情 我创建了一个名为myClassExtensions的类。我可以将任何类对象传递给类,它将迭代属性..所以如果我希望类的初始化属性从null更改为string.Empty,我使用静态类创建扩展方法..这很直接。

public class ClassA 
{
  string X {get; set;}
  string Y {get; set;}
}

 public static class myClassExtensions
 {
    public static void ConvertNullToStringEmpty<T>(this T clsObject) where T : class
    {
        PropertyInfo[] properties = clsObject.GetType().GetProperties();//typeof(T).GetProperties();
        foreach (var info in properties)
        {
            // if a string and null, set to String.Empty
            if (info.PropertyType == typeof(string) && info.GetValue(clsObject, null) == null)
            {
                info.SetValue(clsObject, String.Empty, null);
                // or set some boolean etc since you know the property at this point is of type string
            }
        }
    }
}   

所以我有一个叫ClassA的课我在你的例子中我会做这样的事情

ClassA classaVar = null;
classaVar = (ClassA)FormatterServices.GetUninitializedObject(typeof(ClassA));
myClassExtensions.ConvertNullToStringEmpty<ClassA>(classaVar);

这将使X and Y = string.Empty

的值为

答案 2 :(得分:-1)

那个为我解决这个问题的人删除了他的帖子(我希望不是我意外地完成了这个帖子)

There is fiddle with solution

using System;
using System.Collections.Generic;

class A {
    public string X {get; set;}
    public string Y {get; set;}
    public override string ToString() {
        return "X: " + this.X + " Y: " + this.Y;
    }
 }

public class Program
{
    public static void Main()
    {
        List<A> list = Create<A>("X", new string[] {"value1", "value2"});
        foreach(A item in list) {
            Console.WriteLine(item.ToString());
        }
        list = Create<A>("Y", new string[] {"valueY1", "valueT2"});
        foreach(A item in list) {
            Console.WriteLine(item.ToString());
        }
    }
  public static List<T> Create<T>(string attr, string[] attrValues) where T: new()
    {
        //I want to check if T has attribute attr (let's say "X")

        List<T> ret = new List<T>();
        foreach (string value in attrValues)
        {
            T t = new T();


            foreach (var property in typeof(T).GetProperties())
            {
                if (property.Name == attr) // setting value for x
                {
                    property.SetValue(t, "Value");
                }
            }
            ret.Add(t);
        }
        return ret;
    }
}

谢谢伙计。