相关疑难解决方法(0)

密封关键字会影响编译器对强制转换的看法

我有一种情况,我喜欢编译器的行为解释.给出一点代码:

interface IFoo<T>
{
    T Get();
}

class FooGetter : IFoo<int>
{
    public int Get()
    {
        return 42;
    }
}
Run Code Online (Sandbox Code Playgroud)

以下编译并运行:

static class FooGetterGetter
{
    public static IFoo<T> Get<T>()
    {
        return (IFoo<T>)new FooGetter();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我们更改Foo类的签名并添加sealed关键字:

sealed class FooGetter : IFoo<int> // etc
Run Code Online (Sandbox Code Playgroud)

然后我在以下行得到编译器错误:

 return (IFoo<T>)new FooGetter();
Run Code Online (Sandbox Code Playgroud)

的:

无法将类型'MyNamespace.FooGetter'转换为'MyNamespace.IFoo <T>'

有人可以解释sealed关键字的问题吗?这是针对Visual Studio 2010中的.NET 4项目的C#4.

更新:有趣的是,当我想知道为什么以下代码在sealed应用时修复它时,我偶然发现了这部分行为:

return (IFoo<T>)(IFoo<int>)new FooGetter();
Run Code Online (Sandbox Code Playgroud)

更新:只是为了澄清,当T请求的类型T与具体类型使用的类型相同时,它都运行良好.如果类型不同,则转换在运行时失败,例如:

无法将"MyNamespace.StringFoo"类型的对象强制转换为"MyNamespace.IFoo"1 [System.Int32]'

在上面的示例中,StringFoo : IFoo<string>调用者要求获取 …

c# compiler-errors visual-studio-2010

19
推荐指数
1
解决办法
464
查看次数

标签 统计

c# ×1

compiler-errors ×1

visual-studio-2010 ×1