可以相互比较的自定义类型集
我想构建一组在代表不同类型值的接口之上构建的对象:
integers
strings
datetime
这些对象将能够执行以下操作:
IData intValue = new IntData();
IData intValue2 = new IntData();
bool result = intValue.EqualsTo(intValue2);
IData dateTimeData = new DateTimeData();
IData dateTimeData2 = new DateTimeData();
bool result = dateTimeData.GreaterThan(dateTimeData2);
所以我需要一个接口,但是如何设置比较等的能力? 如果类型是 IEnumerable 呢?
public interface IData
{
}
I want to build a set of objects built on top of an interface that represent different types of values:
integers
strings
datetime
And these objects will be able to perform operations like:
IData intValue = new IntData();
IData intValue2 = new IntData();
bool result = intValue.EqualsTo(intValue2);
IData dateTimeData = new DateTimeData();
IData dateTimeData2 = new DateTimeData();
bool result = dateTimeData.GreaterThan(dateTimeData2);
So I need an interface, but how do I setup the ability to compare etc?
What about if the type is a IEnumerable?
public interface IData
{
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您基本上是在寻找变体类型的 C# 版本。我现在能想到的最接近的东西是 C# 动态:
不幸的是,这是非法的,因此您可以诉诸
并实现其中您想要的逻辑。
Brainwave:
我刚刚想到的另一种方法是提供一个具有隐式转换的统一类 - 是的我不推荐这样做 - 但我确实喜欢想出最有创意的方式来回答原始问题< /em>:
更新 这是一个半完整的示例,说明如何滥用隐式转换来实现您想要的目标(几乎透明地比较析取类型):https://ideone.com/WwI87
I think you are basically looking for a C# version of a variant type. The closest thing that I can think of right now is C#
dynamic
s:Unfortunately, that would be illegal, so you could resort to
and implement the logic you wanted inside that.
Brainwave:
Another approach that just occurred to me, is to provide a unifying class with implicit comversions - yeah I don't recommend this - but I do love to think of the most creative ways in which to answer the original question:
Update Here is a semi-fullblown example of how you could abuse implicit conversions to just about achieve what you want (almost transparent comparison of disjunct types): https://ideone.com/WwI87