覆盖';是';功能

本文关键字:功能 覆盖 | 更新日期: 2024-10-24 01:13:57

我有一个类,所以包含一个异常,也是。

public class ExceptionWrapper
{
    public string TypeName { get; set; }
    public string Message { get; set; }
    public string InnerException { get; set; }
    public string StackTrace { get; set; }
    public ExceptionWrapper() { }
    public ExceptionWrapper(Exception ex)
    {
        TypeName = String.Format("{0}.{1}", ex.GetType().Namespace, ex.GetType().Name);
        Message = ex.Message;
        InnerException = ex.InnerException != null ? ex.InnerException.Message : null;
        StackTrace = ex.StackTrace;
    }
    public bool Is(Type t)
    {
        var fullName = String.Format("{0}.{1}", t.Namespace, t.Name);
        return fullName == TypeName;
    }
}

我想覆盖"is"操作,所以不这么做

if (ex.Is(typeof(Validator.ValidatorException)) == true)

我会这么做

if (ex is Validator.ValidatorException)

有可能吗?怎样

覆盖';是';功能

从Overloadable Operators,可以重载以下运算符:

  • 一元:+, -, !, ~, ++, --, true, false
  • 二进制:+, -, *, /, %, &, |, ^, <<, >>
  • 比较:==, !=, <, >, <=, >=

这些操作员不能超载:

  • 逻辑:&&, ||
  • 数组索引:[]
  • 演员:(T)x
  • 作业:+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
  • 其他:=, ., ?:, ??, ->, =>, f(x), as, checked, unchecked, default, delegate, is, new, sizeof, typeof

此外,比较运算符需要成对重载,如果重载一个,则必须重载另一个:

  • ==!=
  • <>
  • <=>=

直接的答案是:否,is不能被重写(因为它是一个关键字)。

但是你可以通过使用泛型来做一些更优雅的事情。首先定义您的Is()方法,如下所示:

public bool Is<T>() where T: Exception
{
    return typeof(T).FullName == this.TypeName;
}

然后你可以这样写你的比较:

if (ex.Is<Validator.ValidatorException>())

is是一个非重载关键字,但您可以编写这样的扩展方法:

public static bool Is<T>(this Object source) where T : class
{
   return source is T;
}