简体   繁体   English

具有抽象参数的C#抽象方法

[英]C# Abstract methods with abstract parameters

Hi i'm trying to implement a structure where by I need to be able to create an abstract method in an abstract class in C#, which has an abstract object as a parameter.. example- 嗨,我正在尝试实现一种结构,在该结构中,我需要能够在C#的抽象类中创建一个抽象方法,该类具有一个抽象对象作为参数。

public abstract class AbstractMapper
{
     protected abstract AbstractObject doLoad(AbstractObject obj);
}

public abstract class UserMapper
{
     protected override User doLoad(User obj)
     {

     } 
}

In this example the "User" class extends the "AbstractObject" class... This is giving me errors on compile. 在此示例中,“ User”类扩展了“ AbstractObject”类……这给了我编译错误。 Can someone advise on how i should achieve the above? 有人可以建议我如何实现上述目标吗?

Use a generic type parameter on AbstractMapper constrained to be a subtype of AbstractObject : 在被限制为AbstractMapper的子类型的AbstractObject上使用通用类型参数:

public abstract class AbstractMapper<T> where T : AbstractObject
{
     protected abstract T doLoad(T obj);
}

public class UserMapper : AbstractMapper<User>
{
     protected override User doLoad(User obj)
     {
         ...
     } 
}

UserMapper is extending Object class and you are trying to override a method that doens't exist (doLoad). UserMapper正在扩展Object类,并且您试图覆盖不存在的方法(doLoad)。

Also, the signature of the method has a return type of User and you are not returning anything. 此外,该方法的签名的返回类型为User,并且您不返回任何内容。

If you want User class to extend AbstractObject class, then do this: 如果要让User类扩展AbstractObject类,请执行以下操作:

public class User : AbstractObject 
{
      protected AbstractObject doLoad(AbstractObject obj)
      {
            // do something here and return an instance of a class that extends Abstract object
            return null; // added to make it compile
      }
}

Do you know that the access modifier protected means that it is only visible inside the class and in child classes? 您是否知道受保护的访问修饰符意味着它仅在类内部和子类中可见? Read this: https://msdn.microsoft.com/en-us/library/wxh6fsc7.aspx 阅读此: https : //msdn.microsoft.com/en-us/library/wxh6fsc7.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM