CA1047'使成员引发private,public或internal'和C ++ / CLI事件 [英] CA1047 'Make member raise private, public, or internal' and C++/CLI events
问题描述
当我在密封的C ++ / CLI类中声明公共事件时,我会收到代码分析警告CA1047。该警告似乎来自自动生成的受保护成员函数。如何解决此警告?
When I declare a public event in a sealed C++/CLI class, I get Code Analysis warning CA1047. The warning seems to come from auto-generated protected member functions. How can I fix this warning?
这里有一个例子。此代码
Here's an example. This code
ref class Test sealed {
public:
event EventHandler^ blah;
};
产生:
警告:CA1047:Microsoft.Design:使成员'Test :: blah :: raise(Object ^,EventArgs ^)'private,public或internal
warning: CA1047 : Microsoft.Design : Make member 'Test::blah::raise(Object^, EventArgs^)' private, public, or internal
推荐答案
我会更好地记录这个问题。此代码
I'll document the question better. This code
ref class Test sealed {
public:
event EventHandler^ blah;
};
产生:
警告:CA1047:Microsoft.Design:使成员'Test :: blah :: raise(Object ^,EventArgs ^)'private,public或internal
warning: CA1047 : Microsoft.Design : Make member 'Test::blah::raise(Object^, EventArgs^)' private, public, or internal
是的,当你不自己指定事件访问器时,编译器会为你生成它们。它会自动生成add,remove和raise访问器。后者看起来像这样当你看看ildasm.exe:
Yes, when you don't specify the event accessors yourself then the compiler will generate them for you. It auto-generates the add, remove and raise accessors. The latter one looks like this when you look with ildasm.exe:
.method family hidebysig specialname instance void
raise_blah(object value0,
class [mscorlib]System.EventArgs value1) cil managed
{
// etc..
}
family 属性是导致代码分析警告的原因。自动生成的添加和删除访问者当然是公开的。自己写它是一个有问题的解决方法,你真的只想这样做,如果你有一个真正的理由来实现自定义访问器。样板版本如下:
The family attribute is what causes the code analysis warning. The auto-generated add and remove accessors are of course public. Writing them yourself is a questionable workaround, you really only want to do this if you have a real reason to implement custom accessors. The boilerplate version would look like this:
using namespace System::Runtime::CompilerServices;
ref class Test sealed {
private:
EventHandler^ foo;
public:
event EventHandler^ blah {
[MethodImpl(MethodImplOptions::Synchronized)]
void add(EventHandler^ d) { foo += d; }
[MethodImpl(MethodImplOptions::Synchronized)]
void remove(EventHandler^ d) { foo -= d; }
private:
void raise(Object^ sender, EventArgs^ e) {
EventHandler^ handler = foo;
if (handler != nullptr) handler(sender, e);
};
}
};
那么,这当然会抑制警告。我建议你使用[SuppressMessage]属性,如果这不旋转你的螺旋桨。
Well, that certainly suppresses the warning. I recommend you use the [SuppressMessage] attribute if that doesn't spin your propeller.
这篇关于CA1047'使成员引发private,public或internal'和C ++ / CLI事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!