C#使用通用类型简化构造函数中的属性选择器 - c#

如果可能的话,我想简化一些代码。

当前构造函数(T在范围内,在外部类型中定义)

public Column(string propertyName)
{
    PropertyInfo propertyInfo = typeof(T).GetProperty(propertyName);

    _ = propertyInfo ?? throw new ArgumentException(message: $"Property {propertyName} does not exist on {typeof(T).Name}");

    ...
}

我想知道是否可以将property设为Lambda表达式,或者是否可以选择Genet Type T的属性。

这当然是为了使我们的开发更容易,错误更少。

当前使用的
new DataTable<someClass>.Column(nameof(someClass.someProperty))
我想做类似的事情:
new DataTable<someClass>.Column(someClass.someProperty)(不声明新的someClass)

要么
new DataTable<someClass>.Column(t = > t.someProperty)

参考方案

您可以使用以下方法从Expression中提取属性名称

    public static PropertyInfo GetAccessedMemberInfo<T>(this Expression<T> expression)
    {
        MemberExpression? memberExpression = null;

        if (expression.Body.NodeType == ExpressionType.Convert)
        {
            memberExpression = ((UnaryExpression)expression.Body).Operand as MemberExpression;
        }
        else if (expression.Body.NodeType == ExpressionType.MemberAccess)
        {
            memberExpression = expression.Body as MemberExpression;
        }

        if (memberExpression == null)
        {
            throw new ArgumentException("Not a member access", "expression");
        }

        return memberExpression.Member as PropertyInfo ?? throw new Exception();
    }

然后像这样使用

public Column(Expression<Func<T, object>> prop)
{
    PropertyInfo propertyInfo = prop.GetAccessedMemberInfo();
}

new DataTable<someClass>.Column(t = > t.someProperty)

将谓词<T>转换为Func <T,bool> - c#

我有一个包含成员Predicate的类,希望在Linq表达式中使用该类:using System.Linq; class MyClass { public bool DoAllHaveSomeProperty() { return m_instrumentList.All(m_filterExpression); } private IEnumerable&…

与哪些运算符>>兼容 - java

我这里没有什么代码int b=3; b=b >> 1; System.out.println(b); 它可以完美工作,但是当我将变量b更改为byte,short,float,double时,它包含错误,但是对于变量int和long来说,它可以完美工作,为什么它不能与其他变量一起工作? 参考方案 位移位运算符(例如>>)与任何整数类型兼…

通过Maven编译器插件不会发生有限的包含和排除 - java

我正在使用3.6.0版的maven编译器插件,在此我们只想在特定文件夹中编译一个文件,而在该位置编译所有其他文件。例如:在文件夹应用程序中有14个文件,从那我只希望编译1个文件,但它编译了所有文件,如果我要排除,则它也不起作用。 <sourceDirectory>${basedir}/../src/java</sourceDirectory…

当我所有的都是T时,如何返回Interface <T>的实例? - java

我有一个界面:public interface ILoginResult<T> { public T get(); } 我有一个LoginPage对象:public class LoginPage<T> { ... public ILoginResult<T> login(...) { ... } } 我也有一些登录页面对…

<T>如何在这里处理String和Integer - java

我不明白T如何使用Integer和String。如此处显示功能中所示,T同时处理整数和字符串。该代码如何工作?class firstBase { <T> void display(T give_num, T give_String) { System.out.println("The given number is = " +…