如何投射通用属性?

时间:2014-08-13 11:41:52

标签: c# generics

如何遍历一组通用属性并根据它们在给定类中的相应类型进行转换?

我有一个全局设置类如下

    public class GlobalSettingModel<T> 
{
    public Guid SettingId { get; set; }
    public string SettingName { get; set; }
    public Type SettingType { get; set; }
    public T Value { get; set; }
}

然后我有一个SettingsService类,允许获取和设置GlobalSettingModel属性(我在这里包含一个属性&#39; IsUserLogonByPassed&#39;出于示例目的)

 public class SettingsService
{
    private readonly IGlobalSettingStore _settingStore;


    public SettingsService(IGlobalSettingStore settingStore)
    {
        _settingStore = settingStore;
        IsUserLogonByPassed = new GlobalSettingModel<bool>() 
            { SettingName = "IsUserLogonByPassed", SettingType = typeof(bool), Value = false };
    }


    /// <summary>
    /// Gets or sets a value that determines if user logon is bypassed or not
    /// </summary>
    public GlobalSettingModel<bool> IsUserLogonByPassed { get; set; }



    public void SaveSettings()
    {
        var globalSettingProperties = GetType()
            .GetProperties(BindingFlags.Instance | BindingFlags.Public)
            .Where(p => p.PropertyType == typeof(GlobalSettingModel<>));


        foreach (var property in globalSettingProperties)
        {
            var setting = property.GetValue(this, null) as GlobalSettingModel<>;
            if (setting != null) _settingStore.SaveSetting(setting.SettingName, setting.Value);
        }
    }
}

问题出在

行的SaveSettings方法中
var setting = property.GetValue(this, null) as GlobalSettingModel<>;

显然,我得到的是#34; Type Expected&#34;尝试编译时出错。我想知道如何迭代并转换我的所有GlobalSettingModel属性?

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

你做不到。一旦你开始使用反射(这里通过填充globalSettingProperties),你必须一直使用反射。

有一些替代方法,例如让setting属于dynamic类型“感觉”不同,这实际上可能对你有用,但原则上你唯一能做的就是检查运行时的值; dynamic只是将这项工作卸载到编译器和DLR。