使用带有键-对象参数的方法修改类实例字段



这是我最近经常遇到的一个问题。我知道一种让它工作的方法,但我不确定这是否是最好的方法,但似乎这是唯一的方法,而反射似乎是普遍不鼓励的。

我想做的是:我有类实例,我希望能够通过用户输入(字符串)修改。例如:

public class Apple
{
   private String color; //Color of the apple
   private float cost; //Cost of the apple
   private double radius; //Radius of the apple
   public Apple()
   {
      this.color = "";
      this.cost = 0;
      this.radius = 0;
   }
   //The method I am concerned/talking about
   public void setValue(String key, Object value)
   {
      if (key.equalsIgnoreCase("color"))
      {
         this.color = (String)value;
      }
      else if (key.equalsIgnoreCase("cost"))
      {
         this.cost= (float)value;
      }
      else if (key.equalsIgnoreCase("radius"))
      {
         this.radius = (double)value;
      }
   }
}

这被认为是不好的形式吗?我有一个来自用户的键(字符串)来标识他们想要修改的属性/字段,然后我有另一个字符串(值)来指示他们想要更改的值。我确信我可以使用反射,但是

A)我听说它的形式不好,对它皱眉头

B)它在变量名方面要求完美的准确性。如果我有appleColor,而用户放了appleColor,它不会工作。或者,如果我有'applecolor',我希望用户只能够输入'color',等等

我想知道是否有更结构化/面向对象/有用的方法来做到这一点。我想也许每个类都需要"setValue()"有一个与属性/字段匹配的HashMap到它的字符串键,但我不确定是否应该通过"getHashMap()"等方法来实现,该方法返回一个HashMap

hashMap。("颜色",颜色)……或者什么。

任何帮助将是感激的,即使它只是指向我在一个设计模式的方向,处理这个问题。

您希望程序本能地知道要映射到哪个属性?这是不可行的。如果您不想使用反射库,请使用您自己的反射库,并按您想要的方式处理密钥。

比较键,忽略大小写,使用contains I guess

这里有一个算法可以帮助你,根据你的喜好改变它:

public static T Cast<T>(this Object myobj)
    {
        Type objectType = myobj.GetType();
        Type target = typeof(T);
        var x = Activator.CreateInstance(target, false);
        var z = from source in objectType.GetMembers().ToList() where source.MemberType == MemberTypes.Property select source;
        var d = from source in target.GetMembers().ToList() where source.MemberType == MemberTypes.Property select source;
        List<MemberInfo> members = d.Where(memberInfo => d.Select(c => c.Name).ToList().Contains(memberInfo.Name)).ToList();
        PropertyInfo propertyInfo;
        object value;
        foreach (var memberInfo in members)
        {
            propertyInfo = typeof(T).GetProperty(memberInfo.Name);
            PropertyInfo _prop = myobj.GetType().GetProperty(memberInfo.Name);
            if (_prop != null)
            {
                value = _prop.GetValue(myobj, null);
                try
                {
                    propertyInfo.SetValue(x, value, null);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }
        }
        return (T)x;
    }

最新更新