【问题标题】:Accessing base class method using generic T使用泛型 T 访问基类方法
【发布时间】:2016-06-23 18:04:10
【问题描述】:

我有这个基类:

public class BaseEvent
{
    public int EventID { get; set; }

    public int GetEventID()
    {
        return EventID;
    }
}

然后我从那个基础类继承了另一个类:

public class ValidationResult<T> where T : BaseEvent
{
    private void AddEventStatusUpdater(ValidationResult<T> validationResult)
    {
        validationResult.GetEventID();
    }
}

我遇到的问题是我无法从基类访问 GetEventID() 方法。

我认为这可能会发生,因为我使用的是 T 泛型。有没有其他方法可以访问这个方法?

【问题讨论】:

    标签: c# generics base-class


    【解决方案1】:

    您已经开始实现通用接口,而不是从基类继承。我认为您打算执行以下操作:

    public class ValidationResult : BaseEvent
    {
        private void AddEventStatusUpdater()
        {
            var id = this.GetEventID();
        }
    }
    

    【讨论】:

      【解决方案2】:
      public class ValidationResult<T> where T : BaseEvent
      

      T 必须是BaseEvent,而不是ValidationResult&lt;T&gt; 继承自BaseEvent。那是:

      public class ValidationResult<T> : BaseEvent
      

      T 没有任何约束

      这是你想要的吗?

      【讨论】:

        猜你喜欢
        • 2014-07-06
        • 1970-01-01
        • 2011-04-27
        • 1970-01-01
        • 1970-01-01
        • 2022-11-10
        • 2011-12-31
        • 1970-01-01
        相关资源
        最近更新 更多