[英]In C# change a property to read-only at run-time
我正在做一個通用的屬性類。 該泛型將是用戶創建的類,該類模仿配置文件中的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#不允許通用屬性類。 這樣就行不通了。
其次,您不能將屬性更改為僅在運行時讀取。 反射用於檢查已加載類型的元數據,而不更改元數據。
您可以自己備份屬性,但這是一個更大的嘗試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.