属性在方法调用时生成编译错误? [英] Attribute to generate compilation error on method call?
问题描述
我想确保一个方法(实际上是一个我的case中的构造函数)从来没有从代码中显式调用。它应该只在运行时通过反射来调用。为此,我想在方法上应用一个属性,如果方法被调用会产生编译器错误,例如:
I would like to ensure that a method (actually a constructor in my case) is never called explicitly from code. It should only be called through reflection at runtime. To do that, I would like to apply an attribute on the method that would generate a compiler error if the method is called, something like :
[NotCallable("This method mustn't be called from code")]
public void MyMethod()
{
}
我知道我可以使方法私有,但在这种情况下,我不能通过反射在部分信任上下文中调用它...
I know that I could make the method private, but in that case I wouldn't be able to call it through reflection in a partial trust context...
为了完整性,下面是有关为什么需要这么做的更多详细信息:
For completeness, here's more details about why I need to do that :
Singleton< T>
类,基于 Jon Skeet的文章。这是我的代码到目前为止:
I'm implementing a reusable Singleton<T>
class, based on Jon Skeet's article. Here's my code so far :
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);
}
}
(注意我创建T实例的方式, code> Activator.CreateInstance )
(Note the way I create the T instance using Activator.CreateInstance
)
然后我可以使用类:
private class Foo
{
protected Foo()
{
}
public string Bar { get; private set; }
}
并调用 Singleton< Foo& / code>访问实例。
And call Singleton<Foo>.Instance
to access the instance.
在部分信任中,它将无法工作,因为 Foo
构造函数不公开。但是如果我把它公开,没有什么会阻止从代码显式调用它...我知道我可以应用 ObsoleteAttribute
在 Foo
构造函数,但它只会生成一个警告,很多人只是忽略警告。
In partial trust, it won't work because the Foo
constructor is not public. But if I make it public, nothing will prevent calling it explicitly from code... I know I could apply the ObsoleteAttribute
on the Foo
constructor, but it will only generate a warning, and many people just ignore warnings.
您可以使用 ObsoleteAttribute构造函数,它使用一个布尔值,你可以表明调用方法是一个编译错误:
You can use the ObsoleteAttribute constructor that takes a boolean with which you can indicate that calling the method is a compilation error:
[Obsolete("Don't use this", true)]
但是,如果我是你,重新考虑我的设计,因为这不是一个设计良好的API的标志。
However, if I were you, I'd reconsider my design, as doing this isn't a sign of a well-designed API.
这篇关于属性在方法调用时生成编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!