Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用给定表达式访问属性_C#_Lambda - Fatal编程技术网

C# 如何使用给定表达式访问属性

C# 如何使用给定表达式访问属性,c#,lambda,C#,Lambda,我有以下抽象类 abstract public class FooActivator<T> where T : class { protected static Expression<Func<Foo, Bar<T>>> ChosenProperty public void Activate(T Paramater) { using (var foo = new Foo) {

我有以下抽象类

abstract public class FooActivator<T> where T : class
{
    protected static Expression<Func<Foo, Bar<T>>> ChosenProperty

    public void Activate(T Paramater)
    {
         using (var foo = new Foo)
         {
            foo.ChosenProperty.Method(Paramater) //Obviously wrong, How do you do this?
         }
    }
}
现在可以调用
Activate(MyClass参数)
,它将使用

foo.PropertyOfTypeBarMyClass.Method(Paramater)
因为这是表达式中包含的属性


显然,我不能执行
foo.ChosenProperty.Method(Paramater)
,因为
ChosenProperty
Expression
类型的变量,但是,选择表达式所选择的
foo
的任何属性的语法是什么?

我认为您要查找的可能是这样的:

abstract class FooActivator<T> where T : class
{
    protected abstract Func<Foo, Bar<T>> ChosenProperty { get; }

    public void Activate(T param)
    {
        var foo = new Foo();
        ChosenProperty(foo).Method(param);
    }
}

class MyClassFooActivator : FooActivator<MyClass>
{
    protected override Func<Foo, Bar<MyClass>> ChosenProperty
    {
        get { return x => x.SomeBarMyClassProperty; }
    }
}
抽象类FooActivator,其中T:class
{
受保护的抽象Func ChosenProperty{get;}
公共无效激活(T参数)
{
var foo=new foo();
ChosenProperty(foo).方法(param);
}
}
类MyClassFooActivator:FooActivator
{
受保护的重写Func ChosenProperty
{
获取{return x=>x.SomeBarMyClassProperty;}
}
}

您访问ChosenProperty的方式该属性需要是公共的,而不是实例级别的,因为它是静态的。我认为这比它应该的复杂得多。你为什么不告诉我们你想要实现的目标?相关的类名也会有帮助。试试看这里@AdiLester代码更新。是的!这正是我想要的。需要删除
表达式
,只需使用
Func
。非常感谢。
abstract class FooActivator<T> where T : class
{
    protected abstract Func<Foo, Bar<T>> ChosenProperty { get; }

    public void Activate(T param)
    {
        var foo = new Foo();
        ChosenProperty(foo).Method(param);
    }
}

class MyClassFooActivator : FooActivator<MyClass>
{
    protected override Func<Foo, Bar<MyClass>> ChosenProperty
    {
        get { return x => x.SomeBarMyClassProperty; }
    }
}