转换类和设置公共值

Sea*_*ean 1 c# class type-conversion

我们有一系列类,它们来自一个公共类:

public class OurBaseClass
{
    public string StatusMessage { get; set;}
    [other properties]
}

public class ProcessClass : OurBaseClass
{
    public string SomeProcessInformation { get; set;}
    public string SomeMoreProcessInformation { get; set;}
    [other properties]
}
Run Code Online (Sandbox Code Playgroud)

然后我们尝试创建一个函数来设置SpecificProcessClass和current的基本属性(这不起作用):

public object DefaultResponse(string messageText)
{
    return new OurBaseClass
    {
        StatusMessage = messageText,
        [other properties] = ...
    }
};
Run Code Online (Sandbox Code Playgroud)

我们的意图是

ProcessClass resp = (ProcessClass) DefaultResponse("Some Message");
resp.SomeProcessInformation  = "";
resp.SomeMoreProcessInformation  = "";
[other properties] = ...
return resp;
Run Code Online (Sandbox Code Playgroud)

理由是,最大限度地减少重复编码的数量,使功能易于阅读(通过眼睛); 这会引发以下错误.

System.InvalidCastException: Unable to cast object of type 'OurBaseClass' to type 'ProcessClass'
Run Code Online (Sandbox Code Playgroud)

虽然对结果并不完全感到惊讶,因为ProcessClass是从OurBaseClass派生出来的,但我认为可以做到这一点,只是不确定如何......

Cha*_*ger 5

您不能从较少派生的类型转换为更多派生类型,您需要首先创建更多派生类型.

与您当前代码类似的一种解决方案是使用泛型:

public T DefaultResponse<T>(string messageText)
    where T : OurBaseClass, new()
{
    return new T
    {
        StatusMessage = messageText,
    };
}
Run Code Online (Sandbox Code Playgroud)

where约束限制TOurBaseClass或派生类型,并且new()该装置T必须有一个参数构造.您可以在文档中阅读有关它们的更多信息

它可以像这样使用:

ProcessClass resp = DefaultResponse<ProcessClass>("Some Message");
resp.SomeProcessInformation  = "";
resp.SomeMoreProcessInformation  = "";
Run Code Online (Sandbox Code Playgroud)