C# 将派生类指定给返回基类的函数的输出时出错
我在什么地方读到过 派生类(或子类)是其基类的实例C# 将派生类指定给返回基类的函数的输出时出错,c#,asp.net-mvc,C#,Asp.net Mvc,我在什么地方读到过 派生类(或子类)是其基类的实例 public class TransactionCategorisationRuleViewModel : CategorisationRuleViewModel { public long TransactionId { get; set; } [Display(Name="Apply to All Transactions")] public bool IsApplyAll { get; set; } } 鉴于
public class TransactionCategorisationRuleViewModel : CategorisationRuleViewModel
{
public long TransactionId { get; set; }
[Display(Name="Apply to All Transactions")]
public bool IsApplyAll { get; set; }
}
鉴于此,我在继承基类时遇到以下问题
public class TransactionCategorisationRuleViewModel : CategorisationRuleViewModel
{
public long TransactionId { get; set; }
[Display(Name="Apply to All Transactions")]
public bool IsApplyAll { get; set; }
}
我还有一个定义如下的函数:
public CategorisationRuleViewModel GetNewRule()
{
// content
}
但是,当我执行此操作时,会出现一个错误(无法隐式地将类型CategorisationRuleViewModel转换为TransactionCategorisationRuleViewModel。)
让我们举一个简单的例子。我们将有两个班:
class Animal { }
class Horse : Animal { }
我们尝试调用此方法:
public Animal GetNewAnimal()
{
// content
}
因此,如果我们写:
Horse newHorse = GetNewAnimal();
这给了我们一个铸造例外。这是因为GetNewAnimal
返回一个动物。可能是马,也可能是猪。由于编译器不能确定,而您正在进行隐式转换,它会说:“我知道您想要一匹马,但我不能保证它会,所以我放弃。”
解决这个问题的方法是进行显式转换
这告诉编译器返回类型将是一个Horse。但是,如果在运行时无法将返回值转换为Horse,系统将抛出一个InvalidCastException
因此,为了映射到您的示例,请将我帖子中的所有马和动物分别替换为
TransactionCategorizationRuleViewModel
,和CategorizationRuleViewModel
TransactionCategorisationRuleViewModel vmRule =
(TransactionCategorisationRuleViewModel)GetNewRule();
这将修复您的异常,但您正在冒着
GetNewRule
实际返回TransactionCategorizationRuleViewModel
的风险。返回TransactionCategorizationRuleViewModel而不是基类类型可能更容易。马是动物,但动物并不总是马GetNewRule
返回一个“动物”。它可能是一个TransactionCategorizationRuleViewModel
,但可能不是。
TransactionCategorisationRuleViewModel vmRule =
(TransactionCategorisationRuleViewModel)GetNewRule();