代码之家  ›  专栏  ›  技术社区  ›  Musa Hafalir

使用TResult Func<in T,out TResult>

  •  0
  • Musa Hafalir  · 技术社区  · 15 年前

    TResult<in T, out TResult> 我可以通过该委托检索类实例的属性值,如下所示:

    class Program
    {
        class MyClass
        {
            public int MyProperty { get; set; }
        }
    
        static void Main(string[] args)
        {
            Func<MyClass, int> orderKeySelector = o => o.MyProperty;
            MyClass mc = new MyClass() { MyProperty = 3 };
    
            int val = orderKeySelector.Invoke(mc);
        }
    }
    

    我想使用orderKeySelector和MyClass实例为MyProperty赋值。 有什么想法吗?

    2 回复  |  直到 15 年前
        1
  •  1
  •   Jon Skeet    15 年前

    Func<,> 委托表示属性 吸气剂 塞特 ,你需要 Action<MyClass, int>

    Action<MyClass, int> setter = (o, value) => o.MyProperty = value;
    
        2
  •  0
  •   LukeH    15 年前

    你不能用它 orderKeySelector 但您可以创建一个单独的setter委托:

    MyClass mc = new MyClass() { MyProperty = 3 };
    
    Func<MyClass, int> orderKeySelector = o => o.MyProperty;
    int val = orderKeySelector(mc);
    
    Console.WriteLine(val);    // 3
    
    Action<MyClass, int> orderKeySetter = (o, v) => o.MyProperty = v;
    orderKeySetter(mc, 42);
    
    Console.WriteLine(mc.MyProperty);    // 42
    
    推荐文章