您發佈的問題是有些模糊,但它聽起來像你需要定義一個接口,然後讓每個differen類實現該接口。在你的榜樣,在那裏你引用一個「計算」的方法,你只定義一個接口是這樣的:
public interface ICalculator
{
int NumberOne
{
get;
set;
}
int NumberTwo
{
get;
set;
}
int Calculate ();
}
然後當您創建不同的類別,他們將實現這樣的接口:
public class TwoPlusTwoCalculator : ICalculator
{
private int _numberOne;
private int _numberTwo;
public int NumberOne
{
get
{
return this._numberOne;
}
set
{
this._numberOne = value;
}
}
public int NumberTwo
{
get
{
return this._numberTwo;
}
set
{
this._numberTwo = value;
}
}
public TwoPlusTwoCalculator ()
{ }
public TwoPlusTwoCalculator (int numOne, int numTwo)
{
this.NumberOne = numOne;
this.NumberTwo = numTwo;
}
public int Calculate ()
{
return this.NumberOne + this.NumberTwo;
}
}
然後在你的代碼時,你想調用的計算方法,就可以把TwoPlusTwoCalculator,或OnePlusOneCalculator,或實現接口作爲接口的任何其它類的一個實例:
公共無效的GetValue(INT numOne ,int num兩個) {TwoPlusTwoCalculator calculator = new TwoPlusTwoCalculator(numOne,numTwo); PerformCalculation(calculator as ICalculator); PerformCalculation(calculator as ICalculator); }
public int PerformCalculation (ICalculator calculator)
{
return calculator.Calculate ();
}
這就是你想要完成的嗎?