【问题标题】:Add to property easier way?添加到属性更简单的方法?
【发布时间】:2015-01-13 16:33:41
【问题描述】:

我目前必须在这样的列表中加载一些属性:

        List<TestClass> test = new List<TestClass>(); // Loaded with data

        // Get calculated values back as double[]
        double[] calculatedValues = CalculateValue(test);

        // Add the calculated values to the List<TestClass> test object
        for (int i = 0; i < test.Count; i++)
        {
            test[i].Value = calculatedValues[i];
        }


    public int[] CalculateValue(List<TestClass> testClass)
    {
        int[] output = int[testClass.Count];
        // Some calculation
        return output;
    }


    public class TestClass
    {
        public string Name { get; set; }
        public int Value { get; set; }
    }

我真正想做的是这样的:

    public static List<TestClass> CalculateValue(List<TestClass> testClass, string property)
    {
        double[] output = double[testClass.Count];
        // Some calculation
        // output to testClass

        // like:
        // testClass.property = output
        // Would then be like: testClass.Value = output
        return testClass;
    }

我想告诉我的方法应该添加到哪个属性。 有没有可能?

编辑:假设我的 TestClass 中有 Value2、Value3、Value4 等。然后我不能硬编码我的 CalculateValue 方法以始终添加到“Value”属性。希望有意义

希望它有意义。

最好的问候

【问题讨论】:

  • 你当前的代码有什么问题?
  • 假设在我的 TestClass 中我有 10 个需要计算的属性。我将不得不复制+粘贴第一个代码部分 10 次。我会更好地使用底部代码部分,在那里我可以告诉方法,计算值应该添加到哪个属性。
  • 然后使用Dictionary
  • 为什么不在CalculateValue 方法中设置Value?看起来没有理由先将其填充到不同的数组中,然后将值复制过来。
  • @user1281991 你看,这些信息极大地改变了这个问题 :) 一方面,它可能更适合 Code Review,而不是 StackOverflow :)

标签: c# .net


【解决方案1】:

您可以使用委托将值存储在属性中:

List<TestClass> test = new List<TestClass>(); // Loaded with data

// Get calculated values and store in list items
CalculateValue(test, (t, i) => t.Value = i);


public void CalculateValue(List<TestClass> testClass, Action<TextClass, int> store)
{
    int[] output = int[testClass.Count];
    // Some calculation
    for (int i = 0; i < output.Length; i++) {
      store(testClass[i], output[i]);
    }
}

【讨论】:

    【解决方案2】:

    我想你正在寻找DynamicObject。使用 DynamicObject,您可以编写一个通用的动态类,其中包含 Dictionary 或类似内容中的所有属性。通过TryGetMemberTrySetMember 方法,您可以访问属性。

    编辑 MSDN-示例:

    // The class derived from DynamicObject.
    public class DynamicDictionary : DynamicObject
    {
        // The inner dictionary.
        Dictionary<string, object> dictionary
            = new Dictionary<string, object>();
    
        // This property returns the number of elements
        // in the inner dictionary.
        public int Count
        {
            get
            {
                return dictionary.Count;
            }
        }
    
        // If you try to get a value of a property 
        // not defined in the class, this method is called.
        public override bool TryGetMember(
            GetMemberBinder binder, out object result)
        {
            // Converting the property name to lowercase
            // so that property names become case-insensitive.
            string name = binder.Name.ToLower();
    
            // If the property name is found in a dictionary,
            // set the result parameter to the property value and return true.
            // Otherwise, return false.
            return dictionary.TryGetValue(name, out result);
        }
    
        // If you try to set a value of a property that is
        // not defined in the class, this method is called.
        public override bool TrySetMember(
            SetMemberBinder binder, object value)
        {
            // Converting the property name to lowercase
            // so that property names become case-insensitive.
            dictionary[binder.Name.ToLower()] = value;
    
            // You can always add a value to a dictionary,
            // so this method always returns true.
            return true;
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            // Creating a dynamic dictionary.
            dynamic person = new DynamicDictionary();
    
            // Adding new dynamic properties. 
            // The TrySetMember method is called.
            person.FirstName = "Ellen";
            person.LastName = "Adams";
    
            // Getting values of the dynamic properties.
            // The TryGetMember method is called.
            // Note that property names are case-insensitive.
            Console.WriteLine(person.firstname + " " + person.lastname);
    
            // Getting the value of the Count property.
            // The TryGetMember is not called, 
            // because the property is defined in the class.
            Console.WriteLine(
                "Number of dynamic properties:" + person.Count);
    
            // The following statement throws an exception at run time.
            // There is no "address" property,
            // so the TryGetMember method returns false and this causes a
            // RuntimeBinderException.
            // Console.WriteLine(person.address);
        }
    }
    

    【讨论】:

      【解决方案3】:

      你为什么不使用字典?

      public class TestClass
      {
          Dictionary<string,double> values = new Dictionary<string,double>
      
          public Dictionary<string,double> Values {get {return this.values; }}
          public string Name {get;set;}
      }
      
      TestClass testClass = new TestClass();
      testClass.Values["Value1"] = 5.5;
      

      【讨论】:

        猜你喜欢
        • 2011-02-04
        • 2023-04-06
        • 1970-01-01
        • 1970-01-01
        • 2013-05-14
        • 2021-08-07
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多