當我使用泛型接口時,這是一個普通接口的重載,我得到一個錯誤,正常接口的屬性沒有實現。如何用通用接口過載接口
實施例:
public interface IInterface1
{
string Bar1{ get; set; }
string Bar2{ get; set; }
}
public interface IInterface2
{
IInterface1 Foo{ get; }
}
public interface IInterface3<T>:IInterface2 where T:IInterface1
{
new T Foo { get; set; }
}
public class Class1<T> : IInterface3<T> where T : IInterface1
{
public T Foo { get; set; }
}
ERROR: 'Class1' does not implement interface member 'IInterface2.Foo'. 'Class1.Foo' cannot implement 'IInterface2.Foo' because it does not have the matching return type of 'IInterface1'.
但T是類型IInterface1的始終。我究竟做錯了什麼?
EDIT1:
如果我刪除IInterface3,我無法從我的類
EDIT2返回T:
當我改變的Class1的美孚返回,而不是牛逼IInterface1,我還是會得到一個錯誤
EDIT3:
當我改變IInterface3及1至2種方式返回相同的對象它確實有效。 我只想將Class1中的Foo和Foo1組合起來。
(順便說一句:刪除IInterface2的二傳手我並不需要它。)
解決方案:
fejesjoco的答案和裏克 - 讓我想在這最後的解決方案幫助我:
public interface IInterface1
{
string Bar1 { get; set; }
string Bar2 { get; set; }
}
public interface IInterface2
{
IInterface1 Foo { get; }
}
public interface IInterface3<T>:IInterface2 where T:IInterface1
{
new T Foo { get; set; }
}
public class Class1<T> : IInterface3<T> where T : IInterface1
{
private T _foo;
T IInterface3<T>.Foo { get { return _foo; } set { _foo = value; } }
IInterface1 IInterface2.Foo { get { return _foo; } }
}
或
public class Class1<T> : IInterface3<T> where T : IInterface1
{
public T Foo { get; set; }
IInterface1 IInterface2.Foo { get { return Foo; } }
}
的證明布丁的是在品嚐:
public class ImplemetationA : IInterface1
{
public string Bar1 { get; set; }
public string Bar2 { get; set; }
// some extra definitions here
}
public class ImplemetationB : IInterface1
{
public string Bar1 { get; set; }
public string Bar2 { get; set; }
// some extra definitions here
}
public class Problem : Class1<ImplemetationA>
{
public ImplemetationA Foo { get; set; }
}
public class ProblemSolved
{
public IInterface2 Method1()
{
var solvedProblem = new Problem();
solvedProblem.Foo = new ImplemetationA();
return solvedProblem;
}
public void Method2()
{
IInterface2 solvedProblem = Method1();
var result = solvedProblem.Foo;
}
}
我不太清楚你在'IInterface3'裏做了什麼,你在界面範圍內調用'new'到'T'。我從來沒有見過這種情況。這合法嗎?爲什麼你這樣做,如果你不把它存儲在一個變量? – nozzleman