I'd like to add attributes to the properties of a class I'm inheriting from (that I cannot edit because it is generated). I've attempted to do this by redeclaring them in the child class with the "new" keyword and adding the attribute.
This seemed to be working until I noticed some issues it was causing when reflecting on an instance of the child and noticed that the property was not being copied. See the following example:
namespace ConsoleApp
{
class Program
{
public class BaseClass
{
public string Name { get; set; }
}
public class ChildClass : BaseClass
{
new public string Name { get; set; }
}
static void Main(string[] args)
{
var source = new ChildClass();
source.Name = "foo";
var target = new ChildClass();
var properties = typeof(BaseClass).GetProperties();
foreach(PropertyInfo property in properties)
{
var value = property.GetValue(source);
property.SetValue(target, value);
}
Console.WriteLine(target.Name); // Prints nothing
}
}
}
If I inspect the source object after I set the "Name" property, it appears both the parent and child's "Name" property exist on the child, and that only the child's is populated (see image below). I assume the parent's property in the one being copies, since it's null in the target object. I assume this is all due to the use (or misuse) of redeclaring the property with "new".
I'm assuming I'm misusing the new keyword here, but is there another way to add an attribute to base class's property from a child class without the ability to edit the parent class?
Aucun commentaire:
Enregistrer un commentaire