代码之家  ›  专栏  ›  技术社区  ›  Ross Bush

使用基类时如何通过接口强制函数调用约定

  •  0
  • Ross Bush  · 技术社区  · 6 年前

    BaseClass<TResponse, TRequest> where TRequest IsWorkable 具有运输功能 IsWorkable 在流程中。

    我的难题是如何执行 BaseClass 要坚持在基类上强制函数调用约定的接口,而不必在基类的所有子代上声明接口,也就是说,我希望避免修饰基类的所有子代 基类 class NewClass : BaseClass<TResponse, TRequest>, IBase<TResponse, TRequest> .

    NewClass : BaseClass<NewRequest, NewResponse> 相反。

    混乱的编辑

    BaseClass<TResponse, TRequest>, IBaseClass<TResponse, TRequest> where TRequest IsWorkable
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Victor Procure sachin BR    6 年前

    我不得不为WPF中的转换器这样的东西做很多工作,它们共享很多核心功能。

    我的一般方法是对基类进行足够的泛化,这样我就可以创建一个具有简化参数的新方法并将其标记为 abstract 然后从基类调用该方法。这意味着任何继承都必须实现新方法。

    基本转换器.cs:

    public class BaseConverter<TConvert, TConvertBack> : IValueConverter
    {
        protected CultureInfo CurrentCulture { get; set;}
    
        public virtual object Convert(object value, Type targetType, object parameters, CultureInfo culture)
        {
            CurrentCulture = culture;
    
            // Generic methods to check types and conversions....
            var typedValue = (TConvert)value;
    
            return Convert(typedValue, targetType, parameters);
         }
    
         protected abstract Convert(TConvert value, Type targetType, object parameters);
    
         /// Implement rest of interfaces/generic
    }
    

    斯特里ngToBooleanConverter.cs公司:

    public class StringToBooleanConverter : BaseConverter<string, bool>
    {
        protected override object Convert(string value, Type targetType, object parameters)
        {
            bool retVal = false;
            // Convert string to boolean and assign to retVal
            return retVal;
        }
    }