C# 返回对象作为基继承接口(interface)

标签 c# inheritance interface

<分区>

我想返回一个对象,但作为基础继承接口(interface)。 IMasterData 和 IGetValues 由其他项目共享,因此我不太确定我可以进行多少更改。代码是这样的:

public class WithData : IBasicData
{
    public string prop1 { get; set; }
    public string prop2 { get; set; }
    public string prop3 { get; set; }
    public string prop4 { get; set; }
}

public interface IBasicData: IMasterData
{
    string prop3 { get; set; }
    string prop4 { get; set; }
}

public interface IMasterData
{
    string prop1 { get; set; }
    string prop2 { get; set; }
}

public interface IGetValues
{
    IMasterData FillValues(someType element)
}

public class MyClass : IGetValues

public IMasterData FillValues(someType element)
{
    var u = new WithData
    {
        prop1 = element.value1,
        prop2 = element.value2,
        prop3 = element.value3,
        prop4 = element.value4
    };
    return u;
}

我在 return u 中收到一个错误,说它无法将对象 WithData 转换为返回类型 IMasterData。由于继承链,我认为这是可能的。如何返回 IMasterData 类型的对象?

最佳答案

这主要是您的代码并且运行良好。因此,除非您指明问题出在哪里,否则我们无法为您提供太多帮助。

src

public interface IMasterData
{
    string Prop1 { get; set; }
    string Prop2 { get; set; }
}

public interface IBasicData : IMasterData
{
    string Prop3 { get; set; }
    string Prop4 { get; set; }
}

public class WithData : IBasicData
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
    public string Prop3 { get; set; }
    public string Prop4 { get; set; }
}

public class SomeType
{
    public string value1, value2, value3, value4;
}

public interface IGetValues
{
    IMasterData FillValues(SomeType element);
}

public class MyClass : IGetValues
{
    public IMasterData FillValues(SomeType element)
    {
        var u=new WithData()
        {
            Prop1=element.value1,
            Prop2=element.value2,
            Prop3=element.value3,
            Prop4=element.value4
        };
        return u;
    }
}

关于C# 返回对象作为基继承接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36944143/

相关文章:

c# - 从各种字符串创建 DateTime 对象

c# - 如何创建 .aspx 页面列表?

c++ - 指向抽象模板基类的指针?

c# - 使用显式接口(interface)实现

安卓BetterPickers

go - Go 中的接口(interface)实现强制执行

c# - 如何使 Application.Run() 可测试

c++ - 错误:从父类父类派生子类Son时基类未定义

inheritance - 为什么将实例声明为父类(super class)型但将其实例化为子类型,加上里氏替换原则

c# - C#中的默认方法参数