假设我有两张 table ,午餐和晚餐。我知道两者都包含 DateTime 属性“Time”。
如果我有一个通用方法 GetTime,当 T 是 Lunch 时如何返回 db.Lunch.Time 以及当 T 是 Dinner 时返回 db.Dinner.Time?我试图在不使用 typeof 单独测试 T 的情况下实现这一点,而是一般地进行测试。
伪代码:
public T GetTime(日期时间 dt)
{
返回 MyDataContext.GetTable().Where(entity => entity.Time == dt);
}
因此,当我调用 GetTime
问题是我无法在表达式中指定 entity.Time,因为 T 是泛型。我的问题是如何解决这个问题,这样我就可以查找任何 T(知道我所有的实体实际上都有 Time 属性)而不必为 Dinner 和 Lunch 创建特定的方法。
最佳答案
你必须让两个类都实现类似这样的接口(interface):
public interface IMyInterface
{
DateTime Time{get;set;}
}
然后在您的通用方法中:
public void MyMethod<T>(T item) where T: IMyInterface
{
//here you can access item.Time
}
关于c# - 在表达式中引用通用属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/936584/