类型限制

din*_*esh 5 c#

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

例如:

public interface IEntity { }

public class Entity : IEntity {}

public class NonEntity{}

class SampleControl {
    public Type EntityType{get;set;}
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Mar*_*ell 7

这可能是泛型有帮助的场景.使整个类通用是可能的,但不幸的是设计师讨厌泛型; 不要这样做,但是:

class SampleControl<T> where T : IEntity { ... }
Run Code Online (Sandbox Code Playgroud)

现在SampleControl<Entity>有效,SampleControl<NonEntity>但没有.

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

public Type EntityType {get;private set;}
public void SetEntityType<T>() where T : IEntity {
    EntityType = typeof(T);
}
Run Code Online (Sandbox Code Playgroud)

但这对设计师来说无济于事.你可能只需要使用验证:

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