2011-04-06 33 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

相关问题