摘要class投射问题
Abstract class cast issue
我有这个代码:
public abstract class Animal
{
public string Name { get; set; }
}
public class Dog : Animal
{
[JsonProperty("name")]
public new string Name { get; set; }
}
public static void Main()
{
var dog = new Dog
{
Name = "Spark"
};
Console.WriteLine(dog.Name);
Console.WriteLine(((Animal)dog).Name == null);
}
将输出:
Spark
True
为什么 Name
属性 null
转换为 Animal
时?
如果我想将我的对象转换为 Animal
,如何修复它?如何保留属性值?
你所期望的是由override
实现的,所以你必须重写属性:
public override string Name { get; set; }
但是为了做到这一点,你需要将 属性 标记为 abstract
,否则你会得到一个错误:
error CS0506: 'Dog.Name': cannot override inherited member 'Animal.Name' because it is not marked virtual, abstract, or override
Refer to this post. 在那里你可以阅读:
The override modifier may be used on virtual methods and must be used on abstract methods. This indicates for the compiler to use the last defined implementation of a method. Even if the method is called on a reference to the base class it will use the implementation overriding it.
public class Dog : Animal
{
string name = null;
public new string Name { get { return name; } set { name = value; base.Name = name; } } }
}
我有这个代码:
public abstract class Animal
{
public string Name { get; set; }
}
public class Dog : Animal
{
[JsonProperty("name")]
public new string Name { get; set; }
}
public static void Main()
{
var dog = new Dog
{
Name = "Spark"
};
Console.WriteLine(dog.Name);
Console.WriteLine(((Animal)dog).Name == null);
}
将输出:
Spark
True
为什么 Name
属性 null
转换为 Animal
时?
如果我想将我的对象转换为 Animal
,如何修复它?如何保留属性值?
你所期望的是由override
实现的,所以你必须重写属性:
public override string Name { get; set; }
但是为了做到这一点,你需要将 属性 标记为 abstract
,否则你会得到一个错误:
error CS0506: 'Dog.Name': cannot override inherited member 'Animal.Name' because it is not marked virtual, abstract, or override
Refer to this post. 在那里你可以阅读:
The override modifier may be used on virtual methods and must be used on abstract methods. This indicates for the compiler to use the last defined implementation of a method. Even if the method is called on a reference to the base class it will use the implementation overriding it.
public class Dog : Animal
{
string name = null;
public new string Name { get { return name; } set { name = value; base.Name = name; } } }
}