C#中:继承/接口的静态成员? [英] c#: Inherited/interface static member?

查看:430
本文介绍了C#中:继承/接口的静态成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有要求一类具有特定抽象成员的方法吗?事情是这样的:

Is there a way to require that a class have a particular abstract member? Something like this:

public interface IMaxLength
{
    public static uint MaxLength { get; }
}



也许这样的:

Or perhaps this:

public abstract class ComplexString
{
    public abstract static uint MaxLength { get; }
}



我想办法强制类型(通过继承或接口?)有一个静态成员。可以这样做?

I'd like a way enforce that a type (either through inheritance or an interface?) have a static member. Can this be done?

推荐答案

您可以创建一个允许执行的要求作为一个运行时保证自定义属性。这不是一个全面完整的代码示例(你需要调用VerifyStaticInterfaces在应用程序启动时,你需要填写标有TODO),但它确实表明了要领。

You could create a custom attribute that allows enforcing the requirement as a runtime guarantee. This is not a fully complete code sample (you need to call VerifyStaticInterfaces in your application startup, and you need to fill in the marked TODO) but it does show the essentials.

我假设你问这个,所以你能保证成功的基于反射调用指定的方法。

I'm assuming you're asking this so you can guarantee successful reflection-based calls to named methods.

[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;
        }
    }
}

这篇关于C#中:继承/接口的静态成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆