【问题标题】:Issue while getting the type of a class [duplicate]获取类的类型时出现问题[重复]
【发布时间】:2020-01-20 02:21:44
【问题描述】:

我正在阅读 app.config 条目

  <add key="ClassNameSpace.ClassName" value="http://xxxx/xxx.asmx"/>     

我正在尝试获取密钥的类型

  var section = configuration.GetSection(sectionKey.ToString());
  var appSettings = section as AppSettingsSection;
  if (appSettings == null) continue;

  foreach (var key in appSettings.Settings.AllKeys)
  {
      System.Type type = System.Type.GetType(typeof(key).AssemblyQualifiedName);
      var webService = new SecureWebService<type>().Service;
  }

但我遇到了错误

'key' 是一个变量,但用作类型

解决这个问题的任何想法

【问题讨论】:

  • 你不能用变量调用typeof,你需要用一个类型来调用它(这就是警告试图告诉你的) typeof(int) 是有效的。您可以使用 key 调用 GetType 来获取类型实例。
  • 没有人读取异常消息 :( "'key' 是一个变量,但用作类型" 表示key 是一个变量,但你可以像这样使用它typeof(key)中的一个类型
  • 这个“appSettings.Settings.AllKeys”的类型是什么
  • 该键的类型可能只是“字符串”。我认为您希望该键的值获得新类型
  • 所以你的问题是如何通过类名获取类型? stackoverflow.com/questions/11107536/…

标签: c#


【解决方案1】:

typeof() 根据代码文本中使用的类型名称返回类型(类、接口、结构...)的类型。

对于一个类型的字符串表示,你应该使用:

Type type = Type.GetType(key); // full qualified like "namespace.type"
var webService = Activator.CreateInstance(type); // default constructor

【讨论】:

  • 这不会返回 OP 想要的,它会返回键名容器的类型,而不是键代表的类型名。 Type.GetType(key.ToString()) 更有可能产生预期的结果。
  • 我的猜测是 OP 想要得到 Type 的名字。喜欢"System.String" -> typeos(System.String),所以离开System.Type.GetType(key)
  • 确实,key.GetType() 返回“System.String”。我更新了答案。
【解决方案2】:

GetType() 返回一个对象的System.Typeobject。 typeof() 返回一个数据类型的 System.Type 对象。

var section = configuration.GetSection(sectionKey.ToString());
var appSettings = section as AppSettingsSection;
if (appSettings == null) continue;

foreach (var key in appSettings.Settings.AllKeys)
{
    System.Type type = key.GetType();
    var webService = new SecureWebService<type>().Service;
}

【讨论】:

    猜你喜欢
    • 2011-06-16
    • 2023-01-12
    • 2015-11-20
    • 2021-04-10
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 2013-06-27
    • 2018-11-27
    相关资源
    最近更新 更多