在你的基類的例子,「這」不是一個類型的「T」,而是一種「baseClass {T}」。這就是爲什麼它不起作用。我不知道你在這裏試圖完成什麼,但這可能會編譯...
public class baseClass<T>
{
public baseClass<T> method1()
{
return this;
}
}
public class inheritedClass : baseClass<inheritedClass>
{
public baseClass<inheritedClass> method2()
{
return this.method1();
}
}
編輯:我現在理解你的問題。這可能比使用繼承更好的整體方法。您可以轉換接口,如果需要的是一個通用的一個...
public interface FluentStuff
{
FluentStuff method1();
FluentStuff method2();
}
public class MyClass : FluentStuff
{
public FluentStuff method1()
{
return this;
}
public FluentStuff method2()
{
return this;
}
}
但是,如果你堅持使用繼承...
public interface FluentStuff
{
FluentStuff method1();
FluentStuff method2();
}
public abstract class BaseClass : FluentStuff
{
public virtual FluentStuff method1()
{
return this;
}
public abstract FluentStuff method2();
}
public class MyClass : BaseClass, FluentStuff
{
public override FluentStuff method2()
{
return this;
}
}
我非常鼓勵在繼承組成。
泛型實例...
public interface FluentStuff<T>
{
FluentStuff<T> method1();
FluentStuff<T> method2();
}
public abstract class BaseClass<T> : FluentStuff<T>
{
public virtual FluentStuff<T> method1()
{
return this;
}
public abstract FluentStuff<T> method2();
}
public class MyClass : BaseClass<MyClass>, FluentStuff<MyClass>
{
public override FluentStuff<MyClass> method2()
{
return this;
}
}
最後一個例子另一個問題/關注您發佈...
public class SharedFunctionality
{
public void DoStuff1()
{
// common implementation for do stuff 1
}
public void DoStuff2()
{
// common implementation for do stuff 2
}
}
public class MyClass1
{
private readonly SharedFunctionality sharedFunctionality;
public MyClass1()
{
this.sharedFunctionality = new SharedFunctionality();
}
public MyClass1 Method1()
{
this.sharedFunctionality.DoStuff1();
return this;
}
public MyClass1 Method2()
{
this.sharedFunctionality.DoStuff2();
return this;
}
}
public class MyClass2
{
private readonly SharedFunctionality sharedFunctionality;
public MyClass2()
{
this.sharedFunctionality = new SharedFunctionality();
}
public MyClass2 Method1()
{
this.sharedFunctionality.DoStuff1();
return this;
}
public MyClass2 Method2()
{
this.sharedFunctionality.DoStuff2();
return this;
}
public MyClass2 Method3()
{
// do something only this class does
return this;
}
}
class Program
{
static void Main(string[] args)
{
MyClass1 c1 = new MyClass1();
c1.Method1().Method2();
MyClass2 c2 = new MyClass2();
c2.Method1().Method2().Method3();
}
}
什麼?發佈代碼。 – 2014-11-04 04:58:31
@HighCore示例代碼發佈 – Steve 2014-11-04 05:03:23