gpt4 book ai didi

c# - 重构公共(public)代码的最佳方式

转载 作者:太空狗 更新时间:2023-10-30 01:01:17 26 4
gpt4 key购买 nike

考虑以下两个从接口(interface)实现一堆属性的类:

接口(interface)代码:

public interface ISample
{
int x;
string y;
}

第 1 类:

public class SampleA: ISample
{
public int x { get; set; }
public string y { get; set; }
}

第 2 类:

public class SampleB: ISample
{
public int x { get; set; }
[Decorated]
public string y { get; set; }
}

这里唯一的区别是 SampleB 有一个用属性修饰的属性。

这是高度简化的,所讨论的类有更多的属性,但主要区别在于一个类有一些用属性修饰的属性。

将来会出现这样的情况,即会引入更多的类来实现 ISample 接口(interface),并且感觉好像这些类可能应该从抽象类或其他东西继承一些公共(public)代码。

什么是重构此代码的好方法?

最佳答案

试试这个解决方案:Sample 类中的所有属性都是虚拟的,如果你想在派生类中用属性装饰其中的一些属性,只需覆盖 他们。

public class Sample
{
public virtual int x { get; set; }
public virtual string y { get; set; }
}

public class SampleA : Sample
{
}

public class SampleB : Sample
{
[Decorated]
public override string y { get; set; }
}

关于c# - 重构公共(public)代码的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40100187/

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