开发者

C# overriding an interface contract method of a base class

开发者 https://www.devze.com 2023-03-24 20:35 出处:网络
I have created a converter class that uses the IValueConverter interface and InConve开发者_开发知识库rter.It is bound to a DataGrid and it is passed an array of strings in which it determines if the v

I have created a converter class that uses the IValueConverter interface and InConve开发者_开发知识库rter. 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?


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消