C#重写基类的接口契约方法 [英] C# overriding an interface contract method of a base class

查看:244
本文介绍了C#重写基类的接口契约方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个使用IValueConverter接口和InConverter的转换器类。它绑定到DataGrid,并传递一个字符串数组,在其中确定值是否在数组中。

I have created a converter class that uses the IValueConverter interface and InConverter. It is bound to a DataGrid and it is passed an array of strings in which it determines if the value is in the array.

[ValueConversion(typeof(int), typeof(bool))]
public class InConverter : IValueConverter
{
    public object Convert(object value, Type type, object parameter, CultureInfo info)
    {
        String str = value as String;
        String[] compareList = parameter as String[];
        if (str != null)
        {
            foreach (String compare in compareList)
            {
                if (str == compare)
                    return true;
            }
        }
        return false;
    }

    public object ConvertBack(object value, Type type, object parameter, CultureInfo info)
    {
        throw new NotImplementedException();
    }
}

我还有一个名为NotItConverter的对流类,它基本上会返回与InConverter相反,我不想拥有冗余代码。所以,我想象这样做。

I also have a conveter class called NotItConverter which essentially returns the opposite of InConverter and I didn't want to have to have redundant code. So, I pictured doing this.

[ValueConversion(typeof(int), typeof(bool))]
public class NotInConverter : InConverter
{
    public object Convert(object value, Type type, object parameter, CultureInfo info)
    {
        return !(Boolean)base.Convert(value, type, parameter, info);
    }

    public object ConvertBack(object value, Type type, object parameter, CultureInfo info)
    {
        throw new NotImplementedException();
    }
}

但这不起作用。让它在没有警告的情况下进行编译的唯一方法是使NotInConverter中的方法指定override,InConverter中的方法指定virtual。有没有更简单的方法来实现这个目标?

This doesn't work though. The only way to get it to complile without warning is to make the methods in NotInConverter specify override and the methods in InConverter specify virtual. Is there not an easier way to accomplish this?

推荐答案

我认为这是两个建议的组合:

I think it's a combination of both suggestions:

public class NotInConverter : InConverter, IValueConverter
{
  new public object Convert(...)
  {
    return !base.Convert(...);
  }

  new public object ConvertBack(...)
  {
    return !base.ConvertBack(...);
  }
}

这篇关于C#重写基类的接口契约方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆