How to prevent inheritance of a property, so that it is no longer counted in the instantiated object. In the following example, I want object instance B to contain just two properties, namely MyCommonProperty and Name.
Properties must remain public
public class A
{
public string MyCommonProperty { get; set; }
public string MyClassASpecificProperty { get; set; }
}
public class B : A
{
public string Name { get; set; }
}
CodePudding user response:
you can't, but you can:
create a Base Class X with only "MyCommonProperty" and have both A and B inherit from it adding their property.
or
"MyCommonProperty" is actually in a interface which both class implement
CodePudding user response:
Change the modifier of the properties you don't want inherited types to access to private
.
CodePudding user response:
Don't use inheritance when inheritance isn't applicable. Two unrelated classes can still have a common interface without inheritance if you specify an explicit interface
:
public interface ICommonThings
{
string SomeProperty { get; set; }
}
public class Thing1 : ICommonThings
{
public string Thing1Stuff { get; set; }
public string SomeProperty { get; set; }
}
public class Thing2 : ICommonThings
{
public string Thing2Stuff { get; set; }
public string SomeProperty { get; set; }
}
CodePudding user response:
In the same line as Mathieu Guindon suggested, you could use explicit interface implementation to "hide" the property, but I don't see it be a good idea. The trickery would go as follow:
public interface IFoo
{
public string MyCommonProperty { get; set; }
public string MyClassASpecificProperty { get; set; }
}
public class A : IFoo
{
public string MyCommonProperty { get; set; }
string string MyClassASpecificProperty { get; set; }
}
public class B : IFoo
{
public string MyCommonProperty { get; set; }
public string Name{ get; set; }
string IFoo.MyClassASpecificProperty { get; set;}
}