【发布时间】:2015-01-22 09:05:16
【问题描述】:
我正在尝试使用通用方法在 .NET C# 中加载表单设置,其中每个设置都将包含它自己的 try catch 块(当单个设置无效时继续其他设置)。但是我无法弄清楚如何解决将 appsetting 分配给对象的问题。编译器不允许我隐式转换对象的类型。
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));
}
}
【问题讨论】:
-
您不能将
Type类的实例(运行时已知的值)用作泛型参数(需要在编译时已知)。您可以改为使您的方法通用。 -
您的异常处理模式不是一个好主意。 1)您正在捕获所有异常,而不仅仅是您所期望的。 2) 首先避免抛出这些异常,例如使用
TryParse。
标签: c# object casting system.type