2011-04-06 38 views
1

原來的代碼是這樣的:在這裏使用泛型是否合乎邏輯?

public interface IApplicableSystem 
{ 
    string Name { get; } 

    void Apply (); 
} 

public class Effector 
{ 
    public string Name { get; set; } 
} 

public class EffectSystem : IApplicableSystem 
{ 
    Effector Internal { get; set; } 

    public string Name 
    { 
     get { return this.Internal.Name; } 
    } 

    RelayCommand applyCommand; 
    public ICommand ApplyCommand 
    { 
     get 
     { 
      if (applyCommand == null) 
       applyCommand = new RelayCommand (p => this.Apply ()); 

      return applyCommand; 
     } 
    } 

    public void Apply () 
    { 

    } 

    public EffectSystem (Effector value) 
    { 
     this.Internal = value; 
    } 
} 

因此,有許多不同類型的實施IApplicableSystem,所有它們的不同是他們Name財產,Apply方法,這就是類的內部使用的私有Internal屬性的類型。

我應該使用泛型,使他們這樣?:

,這是否合理?主要是這減少了執行IApplicableSystem的其他類型的代碼量。

public abstract class GenericSystem<T> : IApplicableSystem 
{ 
    protected T Internal { get; set; } 

    public virtual string Name 
    { 
     get { return String.Empty; } 
    } 

    RelayCommand applyCommand; 
    public ICommand ApplyCommand 
    { 
     get 
     { 
      if (applyCommand == null) 
       applyCommand = new RelayCommand (p => this.Apply ()); 

      return applyCommand; 
     } 
    } 

    public virtual void Apply () 
    { 

    } 

    public GenericSystem (T value) 
    { 
     this.Internal = value; 
    } 
} 

public class EffectSystemGeneric : GenericSystem<Effector> 
{ 
    public override string Name 
    { 
     get { return GetUniqueName (base.Internal.Name); } 
    } 

    public override void Apply () 
    { 
     Console.WriteLine ("Do something"); 
    } 
} 

回答

2

是的,這是合理的,但是在覆蓋虛擬方法時,必須使用override關鍵字,而不是虛擬的。您可能希望將泛型基類抽象化,以強制實施者提供實現。

+0

謝謝編輯了代碼。 – 2011-04-06 20:11:21

1

是的,通用是有意義的,只是因爲Internal屬性的類型不同。如果沒有,那麼非泛型基類也可以工作。

如果Name屬性將永遠是Internal.Name,那麼你可以聲明類:

public class GenericSystem<T> : IApplicableSystem where T : IName 

哪裏IName是具有Name屬性的接口,並Effector將實現該接口,從而可以移動將Name屬性定義爲基類,而不是在任何地方重寫它。

+0

謝謝,不幸的是名稱屬性的定義發生了變化,但這超出了我的控制範圍:O – 2011-04-06 20:19:52

相關問題