静态接口等效C#

Phi*_*aré 3 c# inheritance static interface

我过去和单身人士一起工作,我知道这是一些解决静态界面问题的人的解决方案.在我的情况下,我不能真正使用单例,因为我有一个我继承的外部类,我无法控制这个(库).

基本上,我有很多继承自"TableRow"(类中的类)的类,我需要这些类中的每一个都实现某个静态方法(例如:GetStaticIdentifier).最后,我需要将这些对象存储在其中一种基类型中,并在此特定类型上使用静态方法.

我的问题是,除了使用单身人士之外还有另一个解决方案吗?在C#中是否有一个我不知道的功能可以帮助我解决这个问题?

O. *_*per 5

看来你想提供一些元信息以及子类TableRow; 可以在不实例化特定子类的情况下检索的元信息.

虽然.NET缺少静态接口和静态多态,但可以(在某种程度上,见下文)使用自定义属性来解决.换句话说,您可以定义一个自定义属性类,用于存储要与类型关联的信息:

[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class StaticIdentifierAttribute : Attribute
{
    public StaticIdentifierAttribute(int id)
    {
        this.staticIdentifier = id;
    }

    private readonly int staticIdentifier;

    public int StaticIdentifier {
        get {
            return staticIdentifier;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以将此自定义属性应用于TableRow子类:

[StaticIdentifier(42)]
public class MyTableRow : TableRow
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以检索(或其他任何子类)的Type实例,并使用该方法检索该类的StaticIdentifier属性.MyTableRowTableRowGetCustomAttributesStaticIdentifierAttribute instance and read out the value stored in its

与静态接口和静态多态性相比的缺点是,确保每个TableRow子类实际上具有该属性不是编译时间; 你必须TableRow在运行时捕获它(并抛出异常,或忽略相应的子类).

此外,你无法确保该属性应用于TableRow子类,但是,虽然这可能有点不整洁,但它并不重要(如果它应用于另一个类,它将不会产生任何影响,如没有代码可以为其他类处理它).