在方法调用上生成编译错误的属性?

Tho*_*que 4 c# attributes compilation

我想确保一个方法(在我的情况下实际上是一个构造函数)永远不会从代码中显式调用.它应该只在运行时通过反射调用.为此,我想在方法上应用一个属性,如果调用该方法会产生编译器错误,如:

[NotCallable("This method mustn't be called from code")]
public void MyMethod()
{
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以将该方法设为私有,但在这种情况下,我无法通过部分信任上下文中的反射来调用它...

为了完整起见,这里有更多关于我为什么需要这样做的细节:

我正在实施一个可重用的Singleton<T>课程,基于Jon Skeet的文章.到目前为止,这是我的代码:

public static class Singleton<T>
{
    public static T Instance
    {
        get
        {
            return LazyInitializer._instance;
        }
    }

    private class LazyInitializer
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static LazyInitializer()
        {
            Debug.WriteLine(string.Format("Initializing singleton instance of type '{0}'", typeof(T).FullName));
        }

        internal static readonly T _instance = (T)Activator.CreateInstance(typeof(T), true);
    }
}
Run Code Online (Sandbox Code Playgroud)

(注意我使用的方法创建T实例Activator.CreateInstance)

然后,我可以使用它与这样的类:

private class Foo
{
    protected Foo()
    {
    }

    public string Bar { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

并致电Singleton<Foo>.Instance访问该实例.

在部分信任中,它不起作用,因为Foo构造函数不公开.但是,如果我公开它,没有什么可以阻止从代码中明确地调用它...我知道我可以ObsoleteAttributeFoo构造函数上应用它,但它只会生成一个警告,很多人只是忽略警告.

那么,是否存在类似于ObsoleteAttribute生成错误而不是警告的属性?

任何建议将不胜感激

Mar*_*ann 7

您可以使用带有布尔值的ObsoleteAttribute构造函数,您可以使用该布尔值指示调用该方法是编译错误:

[Obsolete("Don't use this", true)]
Run Code Online (Sandbox Code Playgroud)

但是,如果我是你,我会重新考虑我的设计,因为这样做并不是设计良好的API的标志.