gpt4 book ai didi

c# - 有没有办法在其内部重建一个对象?

转载 作者:太空狗 更新时间:2023-10-30 00:18:45 25 4
gpt4 key购买 nike

我有一个简单的类,用于 winforms 应用程序的选项。应该有一种方法可以将选项重置为其默认值。我知道我可以添加一个单独的方法来处理这个问题,但是代码会很大(如果我向类添加更多选项):

public SensorOptions()
{
ShowLabelMax = ShowLabelMin = ShowLabelAvr = ShowReceivedTextBox = true;

ChartMaxValue = 140;
ChartMinValue = -40;

ShowChartMinValue = ShowChartMaxValue = ShowChartAvrValue = ShowChartAvrLine = true;

LogFolder = Environment.SpecialFolder.MyDocuments.ToString();
LoggingEnabled = true;
}

public void ResetOptions()
{
this = new SensorOptions(); //can not do. 'this' is read-only
}

我的意思是我可以将构造函数中的代码复制/粘贴到 ResetOptions() 方法中。但是有没有更聪明的方法来实现这一点?

最佳答案

您不能分配this,因为您可能在您的程序中引用了您的类的这个实例。如果您可以通过重新分配 this 来重新构建对象,这将意味着对该类的旧实例的所有引用都将变得无效。

无论您的类(class)中有多少选项,您都可以通过一种或另一种方式初始化它们(因为您在问题中提到了 default value - 所以您需要在某处分配该默认值至少一次,可能在构造函数中)。因此,您的问题的解决方案很简单 - 将所有初始值设定项移动到单独的方法并在构造函数中调用它,然后在每次需要将选项重置为其默认值时调用它。

如果您的任何选项未明确分配默认值,并使用系统默认值并且您不想为每个选项编写 option=default(optionType),您可以使用反射来枚举该类中的所有字段/属性并为它们分配默认值,如下所示:

public static object GetDefault(Type type)
{
if(type.IsValueType) return Activator.CreateInstance(type);
return null;
}
foreach(var field in this.GetType().GetFields())
field.SetValue(this, GetDefault(field.FieldType));
foreach(var prop in this.GetType().GetProperties())
prop.SetValue(this, GetDefault(prop.PropertyType));

关于c# - 有没有办法在其内部重建一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30913981/

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