gpt4 book ai didi

c# - 不能将 System.Type 隐式转换为对象

转载 作者:太空宇宙 更新时间:2023-11-03 13:12:07 25 4
gpt4 key购买 nike

我正在尝试创建在 .NET C# 中加载表单设置的通用方法,其中每个设置都将包含它自己的 try catch block (当单个设置无效时继续其他设置)。但是我无法弄清楚如何解决将应用程序设置分配给对象的问题。编译器不允许我隐式转换对象的类型。

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是类型和 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);
}
}

关于c# - 不能将 System.Type 隐式转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28084770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com