一个为几种类设置属性值的函数

时间:2013-05-30 11:51:11

标签: c# .net

我需要一个在C#4.0中具有以下签名的函数,我迷失在哪里开始:

public static object SetStringPropertiesOnly(object obj)
{

   //iterate all properties of obj
   //if the type of the property is string,
   //return obj
}

最终我想将这个函数用于从不同类派生的几个对象:

myClass1 obj1 = new myClass1 ();
myClass2 obj2 = new myClass2 ();
.....
.....
obj1 = SetStringPropertiesOnly(obj1);
obj2 = SetStringPropertiesOnly(obj2);

所以对象的类型在这里是动态的。

这种方法有可能吗?。

感谢。

5 个答案:

答案 0 :(得分:3)

public static object SetStringPropertiesOnly(object obj)
{
  //Get a list of properties where the declaring type is string
  var stringProps = obj.GetType().GetProperties().Where(x => x.PropertyType == typeof(string)).ToArray();
  foreach (var stringProp in stringProps)
  {
    // If this property exposes a setter...
    if (stringProp.SetMethod != null)
    {
      //Do what you need to do
      stringProp.SetValue(obj, "value", null);
    }
  }
  //What do you want to return?
  return obj;
}

考虑更改方法签名以接受value参数,并将object obj更改为ref,然后您无需返回对象。

答案 1 :(得分:1)

我想你想要返回对象本身。 但是你应该明白原始对象也会被改变。

    public static object SetStringPropertiesOnly(object obj)
    {
        var properties = obj.GetType().GetProperties();
        var strings = properties.Where(p=>p.PropertyType == typeof(string);
        foreach(PropertyInfo property in strings)
        {
            property.SetValue(obj, "Value");
        }
        return obj;
    }

我的方法是创建一个扩展方法并返回void,因为对象会被更改。我还会将希望的字符串添加为参数。

    public static void SetStringProperties(this object obj, string value)
    {
        var properties = obj.GetType().GetProperties();
        var strings = properties.Where(p=>p.PropertyType == typeof(string);
        foreach(PropertyInfo property in strings)
        {
            property.SetValue(obj, value);
        }
        return obj;
    }

您可以像这样调用扩展方法:

obj.SetStringProperties("All strings will have this value");

顺便说一句,您需要这样做的事实可能被认为是“难闻的代码”。如果可以,请重新考虑这个设计。

答案 2 :(得分:1)

难以使用反射。我们也可以将它作为对象扩展(当你使用它时看起来很可爱):

public static class ObjectExtensions
{
    public static T SetStringPropertiesOnly<T>(this T obj) where T : class
    {
        var fields = obj.GetType().GetProperties();

        foreach (var field in fields)
        {
            if (field.PropertyType == typeof (string))
            {
                field.SetValue(obj, "blablalba", null); //set value or do w/e your want
            }
        }
        return obj;

    }
}

和用法:

var obj = someObject.SetStringPropertiesOnly();

答案 3 :(得分:0)

你可以使用一个通用界面,在“IBulkStringEditable”行中。接口应包含方法“void SetStrings()”。 然后,所有类都必须实现此接口和SetStrings方法,其中每个类都有不同的SetStrings内容,具体取决于它具有的字符串属性以及您希望它们具有的值。 然后以这种方式修改SetStringPropertiesOnly函数:

public static IBulkStringEditable SetStringPropertiesOnly(IBulkStringEditable obj)
{
    obj.SetStrings();
    return obj;
}

答案 4 :(得分:0)

您可以在ur方法参数签名中使用dynamic,例如---&gt;

public static object SetStringPropertiesOnly(dynamic obj)
{
    // proceed
}