在单个c#泛型方法中返回可空值和null值
本文关键字:空值 null 返回 单个 泛型方法 | 更新日期: 2023-09-27 18:10:29
是否有可能在c#泛型方法中返回对象类型或Nullable类型?
例如,如果我有一个List
的安全索引访问器,我想返回一个值,我可以稍后用== null
或.HasValue()
检查。
我目前有以下两种方法:
static T? SafeGet<T>(List<T> list, int index) where T : struct
{
if (list == null || index < 0 || index >= list.Count)
{
return null;
}
return list[index];
}
static T SafeGetObj<T>(List<T> list, int index) where T : class
{
if (list == null || index < 0 || index >= list.Count)
{
return null;
}
return list[index];
}
如果我尝试将这些方法合并成一个方法。
static T SafeGetTest<T>(List<T> list, int index)
{
if (list == null || index < 0 || index >= list.Count)
{
return null;
}
return list[index];
}
我得到一个编译错误:
不能将null转换为类型参数'T',因为它可能是不可空的值类型。考虑使用'default(T)'。
但是我不想使用default(T)
,因为在原语的情况下,0
是int
的默认值,是一个可能的真实值,我需要将其与不可用值区分开来。
是否有可能将这些方法合并为一个方法?
(为了记录,我正在使用。net 3.0,虽然我对更现代的c#可以做什么感兴趣,但我个人只能使用3.0的答案)
这里还有一个你可能没有考虑到的选项…
public static bool TrySafeGet<T>(IList<T> list, int index, out T value)
{
value = default(T);
if (list == null || index < 0 || index >= list.Count)
{
return false;
}
value = list[index];
return true;
}
可以让你做这样的事情:
int value = 0;
if (!TrySafeGet(myIntList, 0, out value))
{
//Error handling here
}
else
{
//value is a valid value here
}
在顶部,它与许多其他类型集合的TryXXX
兼容,甚至与转换/解析API兼容。从方法的名称也可以很明显地看出函数是什么,它"尝试"获取值,如果不能,则返回false。
不完全是您想要的,但是可能的解决方法是返回Tuple(或其他包装器类):
static Tuple<T> SafeGetObj<T>(List<T> list, int index)
{
if (list == null || index < 0 || index >= list.Count)
{
return null;
}
return Tuple.Create(list[index]);
}
Null总是意味着不能获得值,单个元组本身意味着一个值(即使值本身可以为Null)。
在vs2015中,你可以在调用:var val = SafeGetObj(somedoublelist, 0)?.Item1;
时使用?.
符号当然,您可以创建自己的通用包装器,而不是Tuple。
如前所述,这不是最优的,但它是一个可行的解决方案,并且有能够看到无效选择和null元素之间的区别的额外好处。
自定义包装器实现的示例:
struct IndexValue<T>
{
T value;
public bool Succes;
public T Value
{
get
{
if (Succes) return value;
throw new Exception("Value could not be obtained");
}
}
public IndexValue(T Value)
{
Succes = true;
value = Value;
}
public static implicit operator T(IndexValue<T> v) { return v.Value; }
}
static IndexValue<T> SafeGetObj<T>(List<T> list, int index)
{
if (list == null || index < 0 || index >= list.Count)
{
return new IndexValue<T>();
}
return new IndexValue<T>(list[index]);
}
您可以做类似但不同的事情。结果几乎是一样的。这依赖于重载和方法解析规则。
private static T? SafeGetStruct<T>(IList<T> list, int index) where T : struct
{
if (list == null || index < 0 || index >= list.Count)
{
return null;
}
return list[index];
}
public static T SafeGet<T>(IList<T> list, int index) where T : class
{
if (list == null || index < 0 || index >= list.Count)
{
return null;
}
return list[index];
}
public static int? SafeGet(IList<int> list, int index)
{
return SafeGetStruct(list, index);
}
public static long? SafeGet(IList<long> list, int index)
{
return SafeGetStruct(list, index);
}
etc...
不是很好吗?
然后我会将整个东西包装在T4模板中,以减少编写代码的数量。
编辑:我的强迫症让我使用illist而不是List。
简短的回答是否定的,这是不可能的。我能想到的最大原因是,如果你能说"我想在这个泛型方法中使用A或B",那么编译起来就会变得复杂得多。编译器如何知道A和B可以以相同的方式使用?你所拥有的已经是最好的了。
我认为您的要求的一个问题是,您正试图使T
既是结构体又是该结构体的各自Nullable<>
类型。因此,我将在类型签名中添加第二个类型参数,使其为:
static TResult SafeGet<TItem, TResult>(List<TItem> list, int index)
但是仍然有一个问题:对于源类型和结果类型之间想要表达的关系,没有一般的约束,因此您必须执行一些运行时检查。
如果你愿意这样做,那么你可以这样做:
static TResult SafeGet<TItem, TResult>(List<TItem> list, int index)
{
var typeArgumentsAreValid =
// Either both are reference types and the same type
(!typeof (TItem).IsValueType && typeof (TItem) == typeof (TResult))
// or one is a value type, the other is a generic type, in which case it must be
|| (typeof (TItem).IsValueType && typeof (TResult).IsGenericType
// from the Nullable generic type definition
&& typeof (TResult).GetGenericTypeDefinition() == typeof (Nullable<>)
// with the desired type argument.
&& typeof (TResult).GetGenericArguments()[0] == typeof(TItem));
if (!typeArgumentsAreValid)
{
throw new InvalidOperationException();
}
var argumentsAreInvalid = list == null || index < 0 || index >= list.Count;
if (typeof (TItem).IsValueType)
{
var nullableType = typeof (Nullable<>).MakeGenericType(typeof (TItem));
if (argumentsAreInvalid)
{
return (TResult) Activator.CreateInstance(nullableType);
}
else
{
return (TResult) Activator.CreateInstance(nullableType, list[index]);
}
}
else
{
if (argumentsAreInvalid)
{
return default(TResult);
}
else
{
return (TResult)(object) list[index];
}
}
}
我的解决方案是写一个更好的Nullable<T>
。它没有那么优雅,主要是你不能使用int?
,但它允许在不知道它是类还是结构体的情况下使用可空值。
public sealed class MyNullable<T> {
T mValue;
bool mHasValue;
public bool HasValue { get { return mHasValue; } }
public MyNullable() {
}
public MyNullable(T pValue) {
SetValue(pValue);
}
public void SetValue(T pValue) {
mValue = pValue;
mHasValue = true;
}
public T GetValueOrThrow() {
if (!mHasValue)
throw new InvalidOperationException("No value.");
return mValue;
}
public void ClearValue() {
mHasValue = false;
}
}
编写GetValueOrDefault
方法可能很诱人,但这正是您将遇到问题的地方。要使用此功能,您必须首先检查值是否存在。