C#类型镜像

时间:2015-11-11 08:42:37

标签: c# .net reflection types

由于缺少更好的术语,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. 

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

感谢。

1 个答案:

答案 0 :(得分:1)

我认为使用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);

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