Changing property type in class that implements interface with object type property

前端 未结 3 1454
臣服心动
臣服心动 2021-01-18 16:48

I\'m writing a TemplateEngine that will allow me to use my own markup in text based files. I\'m wanting to add controls as plugins as the application matures. Currently i\'v

3条回答
  •  甜味超标
    2021-01-18 17:30

    No, the compiler doesn't allow same name fields to be of different data types other than what is defined in the interface in derived classes.

    The properties (since no fields are allowed in interface) should be implemented in the deriving classes and they need to have same data type. So, you cannot probably do it with properties without explicit declaration.

    However, if you make Value to be returned by a function, then it works, but you need to check the return type because the return types should match for the function, otherwise you will get error that interface's function was not implemented.

        interface IControl
        {
            object Value();
        }
        class A : IControl
        {
            string m_value = string.Empty;
            public object Value() { return m_value; }
        };
        class B : IControl
        {
            List m_value = new List();
            public object Value() { return m_value; }
        };
        ....
        object o = new B().Value();
        if (o is List)
            MessageBox.Show("List");
    

    [Update]
    You have to be careful if explicitly defining the body of the properties. Having one name for two properties would be dangerous if implementation is not done carefully.

    These two properties if contain different definition, it would be unexplainable for the final use of the interface and classes.

            public IList Value
            object IControl.Value
    

    See this example:

        ...
        class Repeater : IControl
        {
            List m_Value = new List();
            public IList Value
            {
                get { return this.m_Value; }
                set { this.m_Value = (IList)value; }
            }
            object IControl.Value
            {
                get
                {
                    return this.m_Value;
                }
                set
                {
                    this.m_Value = new List();
                    this.m_Value.Add(new Label());
                    this.m_Value.AddRange((List)value);
                }
            }
        }
        ...
        Repeater b = new Repeater();
        IControl i = b;
        List list = new List();
        list.Add(new Repeater());
        i.Value = list;
    

    You can observe that the list container in Repeater will have different values when data is added via IControl (because of the explicit definition of IContainer.Value).

提交回复
热议问题