覆盖继承的泛型方法

jes*_*ess 25 c# generics

我在基类中有这个代码

 protected virtual bool HasAnyStuff<TObject>(TObject obj) where TObject:class 
  {
      return false;
  }
Run Code Online (Sandbox Code Playgroud)

在儿童班,我压倒一切

protected override bool HasAnyStuff<Customer>(Customer obj) 
  {
    //some stuff
      if Customer.sth etc
      return false;
  }
Run Code Online (Sandbox Code Playgroud)

我收到了这个错误

'''类型参数声明必须是标识符而不是类型'''

我在这做错了什么?

Mar*_*off 43

您不能在派生类中覆盖泛型方法的类型参数.要实现类似的功能,一个选项是让您的基类成为泛型类,并使您的派生类如

class Derived : BaseClass<Customer>
{
     protected override bool HasAnyStuff(Customer customer)
     {
         // ...
     }
}
Run Code Online (Sandbox Code Playgroud)

在哪里BaseClass宣布为

class BaseClass<T> where T : class
{
    // ...
    protected virtual bool HasAnyStuff(T obj)
    {
         // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,根据您的派生类的确切使用方式,您可以HasAnyStuff使用非泛型Customer参数覆盖该方法.

public bool HasAnyStuff(Customer customer)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

但请注意,HasAnyStuff如果您不使用实例,则不会调用new DerivedClass.也就是说,

BaseClass foo = new DerivedClass();
foo.HasAnyStuff(new Customer());
Run Code Online (Sandbox Code Playgroud)

将调用BaseClass泛型方法,而不DerivedClass是非泛型方法.


Zac*_*her 5

与 John Carpenter 的回答类似,您可以使用相同的泛型方法覆盖泛型方法,但只需使用as运算符检查并将其强制转换为所需的类型。这具有使用空测试来检查转换是否有效的额外好处。

基类

protected virtual bool HasAnyStuff<TObject>(TObject obj)
{
    .... // base implementation
}
Run Code Online (Sandbox Code Playgroud)

继承类

protected override bool HasAnyStuff<TObject>(TObject obj)
{
    var customer = obj as Customer;
    if (customer == null) // conversion failed. object is not of type Customer
    {
        return base.HasAnyStuff(obj);
    }

    .... // do stuff with the customer
}
Run Code Online (Sandbox Code Playgroud)