在表达式中引用通用属性
假设我有两张桌子,午餐和晚餐。 我知道两者都包含日期时间属性“时间”。
如果我有一个通用方法 GetTime,当 T 是午餐时我如何返回 db.Lunch.Time,当 T 是晚餐时如何返回 db.Dinner.Time? 我试图在不使用 typeof 单独测试 T 的情况下实现这一目标,而是一般性地测试。
伪代码:
public T GetTime<T>(DateTime dt)
{
return MyDataContext.GetTable<T>().Where(entity => entity.Time == dt);
}
所以当我调用 GetTime
问题是我无法在表达式中指定 entity.Time 因为 T 是泛型。 我的问题是如何解决这个问题,以便我可以查找任何 T(知道我的所有实体实际上都有 Time 属性),而无需为晚餐和午餐创建特定方法。
Let's say I have two Tables, Lunch and Dinner. I know that both contain the DateTime property "Time".
If I have a generic method GetTime, how could I return db.Lunch.Time when T is Lunch and db.Dinner.Time when T is Dinner? I'm trying to achieve this without testing for T individually using typeof, but rather generically.
Pseudocode:
public T GetTime<T>(DateTime dt)
{
return MyDataContext.GetTable<T>().Where(entity => entity.Time == dt);
}
So when I call GetTime<Dinner> it will automatically look in the Dinner Table for all dinner entities with the property time equal to my supplied parameter dt.
The problem is that I can't specifiy entity.Time in my expression because T is a generic. My question is how to get around that, so that I can look for any T (knowing that all my entities in fact have the Time property) without having to create specific methods for Dinner and Lunch.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你必须让两个类都实现一个类似这样的接口:
然后在你的通用方法中:
You'd have to have both classes implement an interface something like this:
And then in your generic method:
您可以使用午餐和晚餐实现的接口,该接口具有名为 Time 的属性
You could use an interface that Lunch and Dinner implement that has a property called Time
当然,您始终可以使用反射。 此外,如果这两种类型实现具有 Lunch 属性的通用接口,您可以使用它。 (我不明白你所说的“表”是什么意思。)
You can always use reflection, of course. Also, if the two types implement a common interface with a Lunch property, you can use that. (I do not understand what you mean by "Table" here.)