将属性添加到派生类的基本属性 [英] Add Attribute to Base Property from Derived Class

查看:60
本文介绍了将属性添加到派生类的基本属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向我继承的类的属性添加属性(我无法编辑,因为它是生成的).我试图通过在子类中使用new"重新声明它们来做到这一点.关键字并添加属性.

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
        }
    }
}

如果我在设置名称"后检查源对象属性,它同时出现父母和孩子的姓名".财产存在于孩子身上,并且只有孩子的财产被填充(见下图).我假设父对象的属性是副本,因为它在目标对象中为空.我认为这完全是由于使用(或误用)用new"重新声明该财产.

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".

我假设我在这里误用了 new 关键字,但是有没有另一种方法可以在无法编辑父类的情况下从子类向基类的属性添加属性?

推荐答案

您可以隐藏属性但使用基础属性的值:

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

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

这篇关于将属性添加到派生类的基本属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆