C# overriding an interface contract method of a base class

拟墨画扇 提交于 2019-12-12 05:49:40

问题


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();
    }
}

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();
    }
}

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?


回答1:


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(...);
  }
}



回答2:


You need to re-specify the interface in the derived class:

public class NotInConverter : InConverter, IValueConverter

This will cause the compiler to create separate interface mappings for the derived class

Proof:

static void Main()
{
    ITest x = new TestDerived();
    x.Name();
}

interface ITest {
    void Name();
}

class TestBase : ITest {
    public void Name() { Console.WriteLine("Base"); }
}
class TestDerived : TestBase, ITest {
    public void Name() { Console.WriteLine("Derived"); }
}

This prints Derived.



来源:https://stackoverflow.com/questions/6932059/c-sharp-overriding-an-interface-contract-method-of-a-base-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!