匹配通用可为空数值类型的条件
给定一个类型T
,有没有办法编写相当于
if (typeof(T).ImplementsProperty(MaxValue))
{
return T ?? typeof(T).MaxValue;
}
else
return T;
注意我不需要类或方法的泛型类型约束,我只需要方法主体中的条件。在这种情况下,T
可以是任何IComparable
。我正在尝试获取要排序的空数字/日期类型,最后出现的空值。
编辑:抱歉,雷指出上述语法中有错误。它应该返回值? typeof(T).MaxValue
给定一个 T 值
或类似的值。希望这是清楚的。
Given a type T
, is there any way to write something equivalent of
if (typeof(T).ImplementsProperty(MaxValue))
{
return T ?? typeof(T).MaxValue;
}
else
return T;
Note that I don't need a generic type constraint on the class or method, I just need a conditional in the method body. T
in this case can be any IComparable
. I'm trying to get null numeric/date types to be ordered with the nulls occurring last.
Edit: Sorry there is an error in the above syntax as pointed out by Ray. It should be returning value ?? typeof(T).MaxValue
given a T value
or something like that. Hope thats clear.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这似乎对我来说适用于可空、值和引用类型:
这是你想要的吗?
This seems to work for me for nullable, value and reference types:
Is this what you wanted?
首先是一个问题。您不能返回 T,它是类型参数。它相当于无效的
return int
。但是您可以查看 T 是否具有 MaxValue 属性,如果有则调用它。下面的代码检查名为
MaxValue
的静态属性并调用它(并假设它是一个 int)。我假设你想要这样的东西:
但这会有它自己的问题,如果你传递一个 int ,它永远不会为 null 并且它总是返回
value
。如果你传入一个可为 null 的 int ,那么它不会实现 MaxValue (实际上你不能传递一个可为 null 的 int ,因为它没有实现 IComparable )。where
T:class, IComparable
的 where 子句可能是最合适的。另一种选择是将开头的检查更改为
But then passing 0 will return MaxValue not 0,这可能不是您想要的。
Firstly a problem. You can't return T which is a Type Parameter. It would be equivalent to
return int
which is invalid.But you can see if T has a
MaxValue
property and call it if it does. The below code checks for the static property calledMaxValue
and calls it (and assumes it's an int).I assume you want something like this:
But this will have it's own problems, if you pass an int in, it will never be null and it will always return
value
. If you pass a nullable int in, then it won't implement MaxValue (actually you can't pass a nullable int, since it doesn't implement IComparable).A where clause of where
T:class, IComparable
may be the most appropriate.Another option would be to change the check at the beginning to be
But then passing 0 would return the MaxValue not 0, which may not be what you want.