我正在尝试制作用于在.NET C#中加载表单设置的通用方法,其中每个设置都包含它自己的try catch块(当一个设置无效时继续进行其他设置)。但是我无法弄清楚如何解决对象的appsetting。 comipler不允许我隐式地转换对象的类型。
private void LoadFormSettings(object o)
{
try
{
//Load settings when application is started
Type t = o.GetType();
// Operator '<' cannot be applied to operands of type 'method group' and 'System.Type'
o = getAppSetting<o.GetType()>("Setting");
// Cannot implicitly convert type 't' to 'object'
o = getAppSetting<t>("Setting");
// The type arguments for method... cannot be inferred from the usage. Try specifying the type arguments explicitly
o = getAppSetting("Setting");
}
catch (Exception ee)
{
}
}
private T getAppSetting<T>(string key)
{
string value = config.AppSettings.Settings[key].Value;
if (typeof(T) == typeof(Point))
{
string[] values = value.Split(',');
return (T) Convert.ChangeType(value, typeof(T));
}
}
答案 0 :(得分:1)
Type
是类型,t
是实例。通用需要类型而不是实例。您只能编写F<Type>()
而不是F<t>()
。在你的情况下,最好写
Type t = o.GetType();
o = getAppSetting("Setting", t);
object getAppSetting(string key, Type t)
{
string value = config.AppSettings.Settings[key].Value;
if (t == typeof(Point))
{
string[] values = value.Split(',');
return Convert.ChangeType(value, t);
}
}
答案 1 :(得分:0)
您可以使用:
public T GetAppSetting<T>(string value) where T : struct
{
string value = config.AppSettings.Settings[key].Value;
return (T)Convert.ChangeType(value, default(T).GetType());
}
var myBoolean = GetAppSetting<bool>("setting");