【发布时间】:2017-11-12 22:55:05
【问题描述】:
我很难通过投射来理解这种情况。 出于演示目的,我创建了这些类:
public interface IFoo {}
public class Foo : IFoo
{
public string Name { get; set; }
}
public class Bar : Foo
{
public string Surname { get; set; }
}
现在,在我的 Main 方法中,我创建了一个返回 IFoo 的静态方法:
class Program
{
static void Main()
{
IFoo iFoo = GetIFoo();
Foo foo = (Foo)iFoo;
//the GetType ext method is executed and it returns Bar
if(foo is Foo)
{
Console.WriteLine($"foo is of type: {foo.GetType()}");
}
Console.ReadLine();
}
static IFoo GetIFoo()
{
var bar = new Bar
{
Name = "MyName",
Surname = "MySurname"
}
return bar;
}
}
问题是:即使我在 GetIFoo 方法中创建了一个 Bar,为什么如果我将 IFoo 转换为 Foo,foo 的类型是 Bar 而不是 Foo?
【问题讨论】:
标签: c# class inheritance polymorphism