Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
        {
            [MyAttribute]
            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?

Properties with the same name

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
163 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can shadow the property but use the base property's value:

[MyAttribute]
new public string Name { 
    get => base.Name; 
    set => base.Name = value;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...