gpt4 book ai didi

c# - 更改派生类中属性的值?

转载 作者:行者123 更新时间:2023-11-30 18:44:32 26 4
gpt4 key购买 nike

我在基类中有一个标有属性的属性,我想更改每个派生类中的一些属性。执行此操作的最佳方法是什么?

据我所知,我必须在我的基类中将属性定义为抽象属性,并覆盖我的每个基类中的属性,并重新定义所有属性。这看起来真的是多余的,我对此并不着迷,因为我将不得不在每个派生类中重复公共(public)属性。

这是我正在尝试做的事情的一个简化示例。我想在派生类中更改 MyAttribute 但保持属性上的所有其他属性相同并在一个地方定义(即我不想重新定义 XmlElement 不止一次)。这可能吗?或者有更好的方法吗?还是我在这里完全滥用属性?

using System;  
using System.Xml;
using System.Xml.Serialization;

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class MyAttribute : System.Attribute
{
public MyAttribute() {}

public string A { get; set; }

public string B { get; set; }
}

public abstract class BaseClass
{
public BaseClass() {}

[XmlElement("some_property")]
[MyAttribute(A = "Value1", B = "Value2")]
public string SomeProperty { get; set; }
}

public class FirstDerivedClass : BaseClass
{
//I want to change value B to something else
//in the MyAttribute attribute on property SomeProperty
}

public class SecondDerivedClass : BaseClass
{
//I want to change value B to yet another value
//in the MyAttribute attribute on property SomeProperty
}

最佳答案

您可以使用 GetCustomAttributes方法返回所有继承级别上的所有属性,或仅返回已实现的类。不幸的是,这不允许您覆盖“AllowMultiple = false”属性。您可能会创建一个调用 GetCustomAttribute 两次的方法,一次使用继承值,一次不使用。然后你可以给非继承值优先于继承值。如果需要,我可以稍后发布示例。

关于c# - 更改派生类中属性的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2699352/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com