属性生成的方法调用编译错误? [英] Attribute to generate compilation error on method call?
问题描述
我想确保一个方法(实际上在我的情况下,构造函数)决不会从code显式调用。它应该只通过在运行时反射被调用。为了做到这一点,我想申请上会产生一个编译器错误的方法的属性,如果该方法被调用时,是这样的:
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 :
我实现一个可重复使用辛格尔顿< T>
类的基础上的乔恩斯基特的文章。这里是我的code迄今:
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实例的方式 Activator.CreateInstance
)
然后我可以用这样的类使用它:
I can then use it with a class like that :
private class Foo
{
protected Foo()
{
}
public string Bar { get; private set; }
}
和呼叫辛格尔顿&LT;富方式&gt; .Instance
来访问实例
在部分信任,它不会工作,因为富
的构造是不公开的。但是,如果我把它公开,什么都不会prevent从code调用它明确。我知道我可以适用 ObsoleteAttribute
在富
的构造函数,但只会生成一个警告,许多人不理会警告。
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
属性,将产生一个错误,而不是警告呢?
So, is there an attribute similar to ObsoleteAttribute
that would generate an error instead of a warning ?
任何建议将AP preciated
Any suggestion would be appreciated
推荐答案
您可以使用 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屋!