C# 类型镜像

C# Type Mirroring

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

例如,应用程序与具有多个 table 的数据库对话,每个数据库在通常类型的代码中都有一个实体:

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

等等

现在,是否有可能 class 动态反映这些实体的类型:

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

例如 T 是动态的 int

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

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

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. 

应用过滤器 filter.Apply(value, operand) 失败,因为 valueobject

谢谢。

我认为 DynamicLinq lib 更适合你。

至于你现在的做法,如果你使用反射来获取值,就用它来调用函数,就像这样:

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);

但无论如何在这种情况下 result 被装箱到 object.