C# 无法将System.Type隐式转换为object

C# 无法将System.Type隐式转换为object,c#,object,casting,system.type,C#,Object,Casting,System.type,我正在尝试在.NET C#中创建加载表单设置的通用方法,其中每个设置将包含自己的try-catch块(当单个设置无效时继续进行其他设置)。但是,我不知道如何将appsetting分配给对象。comipler不允许我隐式转换对象的类型 private void LoadFormSettings(object o) { try { //Load settings when application is started Type t = o.GetType(); //

我正在尝试在.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));
  }
}
private void LoadFormSettings(对象o)
{
尝试
{
//应用程序启动时加载设置
类型t=o.GetType();

//运算符“
Type
是类型,
t
是实例。泛型需要类型而不是实例。您只能编写
F()
而不是
F()
。在您的情况下,最好是编写

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);
  }
}
您可以使用:

    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");
public T GetAppSetting(字符串值),其中T:struct
{
字符串值=config.AppSettings.Settings[key].value;
return(T)Convert.ChangeType(值,默认值(T).GetType());
}
var myBoolean=GetAppSetting(“设置”);

不能将
类型的实例(运行时已知的值)用作泛型参数(需要在编译时已知)。您可以将方法改为泛型。您的异常处理模式不是一个好主意。1)您正在捕获所有异常,而不仅仅是您期望的异常。2)首先避免抛出这些异常,例如使用
TryParse
。非常感谢,它很有效。我没有想到这个选项。