我有使用泛型的問題。我創建一個名爲IProblem
的接口,其中每個問題有結果(答案)和結果(如果它是正確的)如何解決通用類<T>的情況?
public interface IProblem<T>
{
ushort ResultCount { get; }
T[] Results { get; }
bool IsCorrect();
}
public abstract class ProblemBase<T> : IProblem<T>
{
private T[] _results;
private ushort? _resultCount;
public ushort ResultCount
{
get
{
if (_resultCount == null) throw new ArgumentNullException("_resultCount");
return (ushort)_resultCount;
}
protected set
{
if (_resultCount != value)
_resultCount = value;
}
}
public T[] Results
{
get
{
if (_results == null)
_results = new T[ResultCount];
return _results;
}
}
public abstract bool IsCorrect();
}
這是我創造的算術問題的例子,叫做ProblemA
。 T
是decimal
因爲數組類型應是小數(anothers問題也許可能有string
,或int
)
public class ProblemA: ProblemBase<decimal>
{
private decimal _number1;
private decimal _number2;
private Operators _operator;
public decimal Number1
{
get { return _number1; }
set { _number1 = value; }
}
public decimal Number2
{
get { return _number2; }
set { _number2 = value; }
}
public Operators Operator
{
get { return _operator; }
set { _operator = value; }
}
public decimal Result
{
get { return Results[0]; }
set { Results[0] = value; }
}
public ProblemA()
{
this.ResultCount = 1;
}
public override bool IsCorrect()
{
bool result;
switch (_operator)
{
case Operators.Addition:
result = this.Result == (this.Number1 + this.Number2);
break;
case Operators.Subtract:
result = this.Result == (this.Number1 - this.Number2);
break;
case Operators.Multiplication:
result = this.Result == (this.Number1 * this.Number2);
break;
case Operators.Division:
result = this.Result == (this.Number1/this.Number2);
break;
default:
throw new ArgumentException("_operator");
}
return result;
}
}
我使用MVVM,所以我想有一個視圖模型爲每個問題,其中包含ProblemBase<T>
爲財產,但它是如何通用的,我想這將是一個問題,如果把IProblemViewModel
作爲通用。
public interface IProblemViewModel : IViewModel
{
ProblemBase<T> Problem { get; set; }
}
我這樣說是因爲後來計劃使用ObservableCollection<IProblemViewModel>
,所以我不知道如果我寫IProblemViewModel
或IProblemViewModel<T>
沒有任何問題。 在此先感謝。
順便說一句,不留一個實現各地拋出NotImplementedException()等其他地方的一些bug失敗來覆蓋它。做'public abstract bool IsCorrect();'並且儘可能完成接口,但是任何具體的派生類都不能覆蓋它。 – 2012-01-13 03:10:41
@JonHanna感謝Jon的提示,我還在學習它!我會記住 – 2012-01-13 03:17:57