首页 > 解决方案 > 更改后如何获取自动实现属性 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将常量作为默认值回答。

标签: c#.netpropertiesdefault-valuec#-6.0

解决方案


  1. 例如实例属性,只需新建一个实例然后获取默认属性值是最简单的方法。
  2. 对于静态属性,可以在静态构造函数中保留默认值。
    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]);
}

推荐阅读