c# - 更改后如何获取自动实现属性 C# 6.0 的默认编译时值?
问题描述
很快,新的 C# 6.0 Auto-Implemented Property 使我们能够做到这一点
public static bool IsSoundEffects { get; set; } = true; // C# 6.0 allows this
现在在某个地方,我更改了属性IsSoundEffects = false
,所以访问它是错误的。
嗯,那么如何获得实际真正的默认编译时自动实现的属性值。
Some Like :
Type.GetPropertyDefaultValue(IsSoundEffects);
// 真正的编译时 one = true
或者
default(IsSoundEffects) // idk, something like that
为什么我需要那个?
因为我从数据库中填充属性。如果用户需要恢复默认值,则恢复它。例如设置。
看起来很奇怪?我进行了足够多的搜索,但所有关于自动实现功能的示例都没有恢复默认值。
已编辑
提供的最佳方法
xiangbin.pang对反射方式的回答[Short-One]
Christopher将常量作为默认值回答。
解决方案
- 例如实例属性,只需新建一个实例然后获取默认属性值是最简单的方法。
- 对于静态属性,可以在静态构造函数中保留默认值。
public static class MyClass
{
public static int MyProp1 { get; set; } = 100;
public static bool MyProp2 { get; set; } = false;
private static Dictionary<string, object> defaultValues;
static MyClass()
{
defaultValues = new Dictionary<string, object>();
foreach(var prop in typeof(MyClass).GetProperties(BindingFlags.Static| BindingFlags.Public | BindingFlags.NonPublic))
{
defaultValues[prop.Name] = prop.GetValue(null);
}
}
public static (T,bool) GetDefault<T>(string propName)
{
if(defaultValues.TryGetValue(propName, out object value))
{
return ((T)(value), true);
}
return (default, false);
}
}
//test codes
static void Main(string[] args)
{
MyClass.MyProp1 = 1000;
MyClass.MyProp2 = true;
var defaultValueOrProp1 = MyClass.GetDefault<int>("MyProp1");
if(defaultValueOrProp1.Item2)
{
Console.WriteLine(defaultValueOrProp1.Item1);//100
}
var defaultValueOrProp2 = MyClass.GetDefault<bool>("MyProp2");
if (defaultValueOrProp2.Item2)
{
Console.WriteLine(defaultValueOrProp2.Item1);//false
}
}
问题作者添加的以下行:
用于设置具有默认值的属性
private static void ResetPropertyValue(string PropertyName)
{
typeof(Options).GetProperty(PropertyName).SetValue(null,
defaultValues[PropertyName]);
}
推荐阅读
- openai - FileNotFoundError: [WinError 2] 系统找不到指定的文件 (Openai-universe)
- postgresql - 内部 cloudsqladmin 用户的 GCP Pub/Sub 日志显示查询片段/部分数据
- neo4j - Neo4j 有问题
- python - 如何将我的函数的输入和输出从控制台传输到我的 GUI 应用程序?
- grep - 当我使用 egrep 时,使用 \w 在正则表达式匹配中无法正常工作
- swift - 符合类的协议抛出“不能符合”类错误
- python - 如何在模式中安装模式库?
- flutter - Flutter:小部件不会在 Tap 上动态更改
- javascript - TestCafe 中的选择器出错 - 方法 .find()
- android - 如何在 Unity 2018 中构建 Android API Level 29