在c#中,在运行时将属性更改为只读

本文关键字:只读 属性 运行时 | 更新日期: 2023-09-27 18:03:44

我正在制作一个采用泛型的属性类。这个泛型是用户创建的一个类,它模仿配置文件中的appSettings部分。它们为每个键创建一个属性,这个属性允许它们将该键映射到该字段。当他们使用他们的类作为泛型实例化我的类时,我遍历他们的类寻找我的属性,当找到时,我使用他们设置的名称来查找appSetting键,然后将该属性值设置为appSetting值,同时将其转换为他们设置属性的任何类型。

基本上这是一个映射属性,它强类型配置文件中的appSettings。它使得映射是在一个类中完成的,而不是用户必须在他们的代码中内联地完成映射,从而使它变得混乱。不错的映射。

我的最后一步是我想把它们的属性标记为只读,但我不知道如何做到这一点,因为PropertyInfo类的CanWrite属性本身是只读的。

/// <summary>
    /// This class will fill in the fields of the type passed in from the config file because it's looking for annotations on the type
    /// </summary>
    public class StrongConfiguration<T> where T: class
    {
        // this is read only
        public T AppSettings { get; private set; }
        public StrongConfiguration()
        {
            AppSettings = (T)Activator.CreateInstance(typeof(T));
            // find properties in this type that have the ConfigAttribute attribute on them
            var props = from p in AppSettings.GetType().GetProperties()
                        let attr = p.GetCustomAttributes(typeof(ConfigAttribute), true)
                        where attr.Length == 1
                        select new { Property = p, Attribute = attr.First() as ConfigAttribute };
            // find the config setting from the ConfigAttribute value on each property and set it's value casting to the propeties type
            foreach (var p in props)
            {
                var appSettingName = ConfigurationManager.AppSettings[p.Attribute.ConfigName];
                var value = Convert.ChangeType(appSettingName, p.Property.PropertyType);
                p.Property.SetValue(AppSettings, value);
                // todo: I want to set this propety now as read-only so they can't change it but not sure how
            }
        }
    }

在c#中,在运行时将属性更改为只读

两件事,一是c#不允许通用属性类。所以这行不通。

第二,不能在运行时将属性更改为只读。反射用于检查所加载类型的元数据,而不是更改元数据。

您可以自己备份属性,但这是一个更大的努力。