[英]Constructor can't accept input type Expression<Func<T, TResult>> in C#
I want to create the class Foo
as follows.我想按如下方式创建类
Foo
。
The Foo
constructor input expression has to get some member of Type T
to do some work. Foo
构造函数输入表达式必须让Type T
的一些成员来做一些工作。
class Foo<T>
{
public Foo<TResult>(Expression<Func<T, TResult>> selector)
{
List<string> memberNames = typeof(TR).GetProperties().Select(p => p.Name).ToList();
....//some work on memberNames
}
}
and create Foo<T>
instance by this code:并通过以下代码创建
Foo<T>
实例:
Foo<ClassA> foo = new Foo<ClassA>(u=>new{u.Property1, u.Property2});
However, this did not work and gave the following error:但是,这不起作用并给出了以下错误:
Constructor can't have Generic type TResult.
How can I fix this?我怎样才能解决这个问题?
Edit:编辑:
After struggling to understand the expression I found an answer and have written it as an answer.在努力理解表达后,我找到了答案并将其写为答案。
You can move the logic outside of consrtuctor to separate method.您可以将构造函数之外的逻辑移至单独的方法。 Instead of using constructor to create Foo - you can use static method, like this:
而不是使用构造函数来创建 Foo - 您可以使用静态方法,如下所示:
class Foo<T> {
private Foo() {
}
private void Init<TResult>(Expression<Func<T, TResult>> selector) {
List<string> memberNames = typeof(TResult).GetProperties().Select(p => p.Name).ToList();
//some work on memberNames
}
public static Foo<T> Create<TResult>(Expression<Func<T, TResult>> selector) {
var foo = new Foo<T>();
foo.Init(selector);
return foo;
}
}
And use it like this:并像这样使用它:
Foo<ClassA> foo = Foo<ClassA>.Create(u=>new{u.Property1, u.Property2});
I solve that as follow我解决如下
class ClassA
{
public int MyProperty { get; set; }
public int MyProperty2 { get; set; }
}
class Foo<T>
{
public Foo(Expression<Func<T, Object>> selector)
{
var props = ((NewExpression)selector.Body).Members.Select(p => p.Name).ToList();
}
}
Foo<ClassA> foo = new Foo<ClassA>(u => new { u.MyProperty, u.MyProperty2 });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.