我有以下方法,目前在int上有效?变量。我想将它扩展到任何可以为空的数值变量(例如,decimal?,double?,等等)
public static bool IsNullOrInvalid(this System.Nullable<int> source)
{
return (source == null || source == -1);
}我怎么才能成功呢?
发布于 2011-04-01 00:47:55
棘手的一点是找出在每种情况下“无效”的含义。如果“任何小于数据类型缺省值的值”都可以,您可以尝试:
public static bool IsNullOrNegative<T>(this T? source)
where T : struct, IComparable<T>
{
return source == null || source.Value.CompareTo(default(T)) < 0;
}EDIT:正如注释中所指出的,没有“数字”约束--在每一个与其本身具有可比性的值类型上调用此方法都是有效的,比如DateTime。没有办法避免这一点-添加更多的约束可能会略微减少集合,但不是完全减少。
为了准确地与-1进行比较,您需要能够计算出每个类型的值"-1“。没有通用的方法可以做到这一点。您可以手动构建一个“我感兴趣的每种类型的-1”的Dictionary<Type, object>,但这将非常难看。
如果-1无效,那么-2真的有效吗?这对我来说似乎很奇怪。
发布于 2011-04-01 00:48:06
我不认为这是可能的,因为要使这个泛型,它必须是所有类型的泛型,而invalid是特定于整数的。如果您只是重载该方法(double、float等),编译器应该会在您键入时找出您想要哪一个
(0.0).IsNullOrValid()发布于 2011-04-01 00:53:11
你不能,要实现这一点,你需要
public static bool IsNullOrInvalid<T>(this System.Nullable<T> source) where T : Numeric但是在c#中没有用于数字的Numeric基类。
问题出在source == -1上,没有适用于-1的公共类或接口。
你可以破解-1
public static bool IsNullOrInvalid<T>(this System.Nullable<T> source, T invalid)
where T: struct, IEquatable<T>
{
return (source == null || source.Value.Equals(invalid));
}但是你需要像这样打电话
int? foo = -1;
var isInvalid = foo.IsNullOrInvalid(-1);https://stackoverflow.com/questions/5503309
复制相似问题