Hide Equals and ReferenceEquals
I am creating an internal class to provide a construct for th开发者_StackOverflow中文版e Contract pattern.
using System;
using System.Runtime.Serialization;
namespace DCS2000.Common35.Core
{
public class Assertion
{
public static void Ensure(bool test)
{
if (!test)
{
throw new PreconditionException("Precondition test failed");
}
}
public static void Ensure(object obj)
{
if (obj == null)
{
throw new PreconditionException("Precondition null object failed");
}
}
public static void Require(bool test)
{
if (!test)
{
throw new PostconditionException("Postcondition test failed");
}
}
public static void Require(object obj)
{
if (obj == null)
{
throw new PostconditionException("Postcondition null object failed");
}
}
}
}
When a developer goes to use this they will see these as options in Intellisense:
- Ensure
- Equals
- ReferenceEquals
- Require
This is confusing and I am wondering if there is a way to hide Equals and ReferenceEquals.
NOTE: I have already tried this, but it did not work for me:
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
return base.Equals(obj);
}
To add to Matti's answer, EditorBrowsableState.Never
depends on the user's Visual Studio settings under Options, Text Editor, C#, General.
It only takes effect if the user has 'Hide advanced members' turned on. Visual Studio defaults to showing all members.
Use:
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
throw new Exception("Assertion does not implement Equals, use Ensure or Require");
}
[EditorBrowsable(EditorBrowsableState.Never)]
public new bool ReferenceEquals(object objA, object objB)
{
throw new Exception("Assertion does not implement ReferenceEquals, use Ensure or Require");
}
This will hide the members if the developer has appropriate VS settings set, and will immediately notify, alas during run-time, the developer that they are inappropriately using Equals or ReferenceEquals, should they inadvertently use it in the code base.
To be honest, I think anybody who calls themselves a .NET developer should be used to having those methods around and ignoring them when not needed.
If you really want to hide them, and if they're both overridable (I forget if ReferenceEquals
is because I've never used it), you could override them as private override
.
Okay, that doesn't work. Now that I looked at it, private override
makes no sense, protected override
isn't quite allowed either and private new
and protected new
make new methods while the base class method is still accessible. I don't think you can hide them with access modifiers at all.
And it seems the whole thing was about static methods anyways. Gee, I really failed this one.
精彩评论