相关疑难解决方法(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万
查看次数

无法从用法中推断出方法的类型参数

也许我工作过度,但这不是编译(CS0411).为什么?

interface ISignatur<T>
{
    Type Type { get; }
}

interface IAccess<S, T> where S : ISignatur<T>
{
    S Signature { get; }    
    T Value { get; set; }
}

class Signatur : ISignatur<bool>
{
    public Type Type
    {
        get { return typeof(bool); }
    }
}

class ServiceGate
{
    public IAccess<S, T> Get<S, T>(S sig) where S : ISignatur<T>
    {
        throw new NotImplementedException();
    }
}

static class Test
{
    static void Main()
    {
        ServiceGate service = new ServiceGate();
        var access …
Run Code Online (Sandbox Code Playgroud)

c# type-inference

50
推荐指数
2
解决办法
11万
查看次数

标签 统计

c# ×2

generics ×1

type-inference ×1