C#类型镜像

本文关键字:镜像 类型 | 更新日期: 2023-09-27 18:21:38

在C#中有没有可能拥有我可以称之为动态类型镜像的东西,因为没有更好的术语?

比方说,一个应用程序与一个有多个表的数据库进行对话,每个表都有一个通常类型的代码实体:

public class SomeEntity
{
    int ID { get; set; }
    string Name { get; set; }
};

等等。

现在,有没有可能拥有一个动态镜像这些实体类型的类:

public class FilterType<T, U>
{
    T Field1;
    bool Apply<T>(T operand, T comparand);
};

使得T是动态的int

如果我没记错的话,泛型是由编译时决定的,所以这是不可能的。有什么可以近似这种行为吗?

我需要它来过滤表中的字段,理想情况下,我希望它尽可能通用,耦合最小。为了添加更多内容,这里有一些来自我的过滤器类型的代码:

public interface IFilter
{
    string Representation { get; }
}
public interface IFilterBinary : IFilter
{
    bool Apply<T>(T source, T operand1, T operand2) where T : IComparable;
}
public interface IFilterUnary : IFilter
{
    bool Apply<T>(T source, T operand) where T : IComparable;
}
public class IsGreaterOrEqual : IFilterUnary
{
    public string Representation { get; } = ">=";
    public bool Apply<T>(T source, T operand) where T : IComparable
    {
        return source.CompareTo(operand) >= 0;
    }
}

这个问题是,当我尝试使用过滤器时,我遇到了一个障碍:

var property = typeof (User).GetProperties().Single(x => x.Name == rule.FieldName);
var fieldValue = property.GetValue(user);
var fieldType = property.PropertyType;
var value = Convert.ChangeType(fieldValue, fieldType); // Here the return type is `object`, so this line is useless. 

由于valueobject,所以应用滤波器filter.Apply(value, operand)失败。

谢谢。

C#类型镜像

我认为使用DynamicLinq库更适合您。

至于您当前的方法,如果您使用反射来获取值,只需使用它来调用函数,如下所示:

var property = typeof (User).GetProperty(rule.FieldName);
var fieldValue = property.GetValue(user);
var fieldType = property.PropertyType;
var result = filter.GetType().GetMethod("Apply").MakeGenericMethod(fieldType).Invoke(filter, fieldValue, operand);

但无论如何,在这种情况下结果被装箱到对象