c#:Inherited/interface静态成员?

cor*_*ore 3 c# oop inheritance static interface

有没有办法要求一个类有一个特定的抽象成员?像这样的东西:

public interface IMaxLength
{
    public static uint MaxLength { get; }
}
Run Code Online (Sandbox Code Playgroud)

或许这个:

public abstract class ComplexString
{
    public abstract static uint MaxLength { get; }
}
Run Code Online (Sandbox Code Playgroud)

我想强制一种类型(通过继承或接口?)具有静态成员的方式.可以这样做吗?

Sam*_*ell 6

您可以创建一个自定义属性,允许将需求强制为运行时保证.这不是一个完整的代码示例(您需要在应用程序启动时调用VerifyStaticInterfaces,并且需要填写标记的TODO),但它确实显示了基本要素.

我假设你问这个,所以你可以保证成功的基于反射的命名方法调用.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false, AllowMultiple = true)]
internal sealed class StaticInterfaceAttribute : Attribute
{
    private readonly Type interfaceType;

    // This is a positional argument
    public StaticInterfaceAttribute(Type interfaceType)
    {
        this.interfaceType = interfaceType;
    }

    public Type InterfaceType
    {
        get
        {
            return this.interfaceType;
        }
    }

    public static void VerifyStaticInterfaces()
    {
        Assembly assembly = typeof(StaticInterfaceAttribute).Assembly;
        Type[] types = assembly.GetTypes();
        foreach (Type t in types)
        {
            foreach (StaticInterfaceAttribute staticInterface in t.GetCustomAttributes(typeof(StaticInterfaceAttribute), false))
            {
                VerifyImplementation(t, staticInterface);
            }
        }
    }

    private static void VerifyInterface(Type type, Type interfaceType)
    {
        // TODO: throw TypeLoadException? if `type` does not implement the members of `interfaceType` as public static members.
    }
}

internal interface IMaxLength
{
    uint MaxLength
    {
        get;
    }
}

[StaticInterface(typeof(IMaxLength))]
internal class ComplexString
{
    public static uint MaxLength
    {
        get
        {
            return 0;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 谁是懦夫一直在投票我没有解释?如果我错了,至少告诉我,以后我不会犯同样的错误.*来吧!* (2认同)