Is there a compact way of telling the C# compiler to use the base Equals and == operator?
I am fairly new to C#, and I come from a C++ background.
I have defined a struct, and the (Microsoft) compiler keeps popping up the error CA1815 "'GenericSendRequest' should override Equals"
I read a bit around and saw that C# structs derive from ValueType which impleents a generic Equals using reflection. This confused me more:
- Why does the compiler create an error instead of a warning if its just a performance issue?
- Why does it define that generic Equals in the first place if it's not going to let you use it?
So how can I tell the开发者_运维百科 compiler that "I don't care"? Something similar with just declaring assignment operator in a C++ class without providing definition to acknowledge that I know what I am doing.
So far my solution has been to include:
public static bool operator ==(GenericSendRequest lhs, GenericSendRequest rhs)
{
return lhs.Equals(rhs);
}
public static bool operator !=(GenericSendRequest lhs, GenericSendRequest rhs)
{
return !lhs.Equals(rhs);
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
//Yes, it also makes me override GetHashCode since I'm overriding Equals.
public override int GetHashCode()
{
return base.GetHashCode();
}
in my struct, which is just awful.
Edit: This is the struct definition:
public struct GenericSendRequest
{
public LiveUser Sender;
public LiveUser[] Receivers;
public Message Msg;
public ServiceHttpRequest HttpRequest;
}
Its usage is just multiple return values from a function:
public static GenericSendRequest CreateGenericSendRequest(...);
This is definitely not an error, its only a warning - and that warning even only will show up if you have enabled code analysis as part of your build. It's a suggestion for performance optimization - take it that way.
Edit:
Turns out this is configurable:
Go to Project Properties | Code Analysis |
Run this rule set..
Open
Expand the Performance
section - for CA 1815 you can select whether you want this to be a warning, an error or none.
You got a little lost in the IDE somehow, this is not a compiler error. It is a code analysis error, performed by a tool known as FxCop. You can disable it with Analyze + Configure, untick the "Enable Code Analysis on Build" option.
The tool is a little naggy, its use is more as a reminder that you might have done something unwise. Which in this case is pretty unlikely, this is not the kind of struct you can meaningfully compare without doing a lot of work. It is a performance warning, the default equality comparer for a struct uses reflection and that's not very efficient. But you'll make it a lot less efficient by implementing a correct version of Equals().
There is something else wrong, a struct in C# does not at all behave like a struct in C++. It should only be used for simple values that can be easily copied, given that it is a value type. You should make this a class instead. Solves the analysis error too.
精彩评论