类型限制

我们可以将类的Type属性限制为特定类型吗?

例如:

public interface IEntity { } public class Entity : IEntity {} public class NonEntity{} class SampleControl { public Type EntityType{get;set;} } 

假设sampleControl是UI类(可能是Control,Form,..),其EntityType属性的值应该只接受typeof(Entity)的值,而不是typeof(NonEntity)我们如何限制用户赋予特定的在设计时键入(bcause – Sample是我们可以在设计时设置其属性的控件或表单),这在C#.net中是否可行

我们怎样才能使用C#3.0实现这一目标?

在我上面的类中,我需要Type属性,对此必须是IEntity之一。

这可能是generics有帮助的场景。 使整个类具有通用性是可能的,但遗憾的是设计师讨厌generics; 不要这样做,但是:

 class SampleControl where T : IEntity { ... } 

现在SampleControl工作,而SampleControl则不工作。

同样,如果在设计时没有必要,你可以有类似的东西:

 public Type EntityType {get;private set;} public void SetEntityType() where T : IEntity { EntityType = typeof(T); } 

但这对设计师来说无济于事。 您可能只需要使用validation:

 private Type entityType; public Type EntityType { get {return entityType;} set { if(!typeof(IEntity).IsAssignableFrom(value)) { throw new ArgumentException("EntityType must implement IEntity"); } entityType = value; } } 

您必须创建一个inheritance自System.Type的类EntityType。

 public class EntityBaseType : System.Type { } 

在你的控制..

 public EntityBaseType EntityType{get;set;} 

我不建议这样做。

当然你可以在set语句中进行类型检查。

 class SampleControl { public Type EntityType{get; set { if(!value.Equals(typeof(Entity)) throw InvalidArgumentException(); //assign } } } 

另一种选择是,您可以针对实体类型进行编码,该实体类型是您案例中所有实体的基类,如果我假设正确的话。