相关疑难解决方法(0)

如何从C#中的泛型方法返回NULL?

我有一个通用的方法与这个(虚拟)代码(是的我知道IList有谓词,但我的代码不使用IList但其他一些集合,无论如何这与问题无关...)

static T FindThing<T>(IList collection, int id) where T : IThing, new()
{
    foreach T thing in collecion
    {
        if (thing.Id == id)
            return thing;
    }
    return null;  // ERROR: Cannot convert null to type parameter 'T' because it could be a value type. Consider using 'default(T)' instead.
}
Run Code Online (Sandbox Code Playgroud)

这给了我一个构建错误

"无法将null转换为类型参数'T',因为它可能是值类型.请考虑使用'default(T)'."

我可以避免这个错误吗?

c# generics

519
推荐指数
9
解决办法
17万
查看次数

在单个C#泛型方法中返回nullable和null?

在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];
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试将方法组合到一个方法中.

static T SafeGetTest<T>(List<T> list, int index)
{
    if (list …
Run Code Online (Sandbox Code Playgroud)

c# generics nullable

11
推荐指数
3
解决办法
1634
查看次数

静态构造函数和异常

如果静态构造函数抛出异常并且未处理它会发生什么?

它会一直存在,直到应用程序域存活?

c# constructor

7
推荐指数
1
解决办法
1664
查看次数

标签 统计

c# ×3

generics ×2

constructor ×1

nullable ×1