2016-04-29 83 views
2

我想返回一个对象,但是作为基础继承接口。 IMasterData和IGetValues由其他项目共享,所以我不太确定我可以做出的改变的数量。该代码是这样的:C#返回对象作为基础继承接口

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; 
} 

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

+0

你试过投?返回你的IMasterData –

+0

我收到一个异常,“无法投入'WithData'类型的对象键入'IMasterData'。” – user1970778

+1

非常奇怪,你的代码在这里工作正常,你能提供编译器给出的错误吗? –

回答

1

这主要是你的代码,它运行良好。所以除非你指出问题出在哪里,否则我们无法帮到你。

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; 
    } 
}