【问题标题】:Verification of object type to string[] is not working对字符串 [] 的对象类型的验证不起作用
【发布时间】:2017-07-11 20:14:02
【问题描述】:

谁能帮我看看为什么我的病情不起作用? 为了更清楚,我希望得到一个 T 类型,看看这个类型是否是字符串 []。 在我下面的代码中与类型不匹配,任何人都可以告诉我我做错了什么?

public T GetTotalMemoryValue<T>()
{
    object result = null;
    result = typeof(T);

    if(result.GetType() == typeof(string[]))
    {
        Convert.ChangeType(result, typeof(string[]));

        try
        {  
          ...
        }
        return (T)(object) buffer;

    }
}

buffer 是一个字符串数组。

【问题讨论】:

  • 一方面,你没有返回一个值......这就是你所说的“总是失败”的意思吗?代码甚至是如何编译的?
  • 你想达到什么目的?错误是什么?
  • 这个sn-p目前无法编译,是否需要帮助才能编译或运行?请发布update your question 以帮助我们更好地了解您的问题。
  • 没有return语句,怎么可能编译通过
  • 阅读本文可能会有所帮助:stackoverflow.com/questions/5737840/…

标签: c#


【解决方案1】:

由于我不知道您真正想要实现什么,因此比较失败的原因如下:

var result = typeof(T); // is the same as below
Type result = typeof(T);

typeof() 将返回 TypeType.GetType() 将始终返回 Type

正确的比较应该是:

if(typeof(T) == typeof(string[]) 
{
    // code goes here
}

【讨论】:

  • 不完全。 typeof(string[]) 返回一个 System.String[] 并且 result.GetType() 返回一个 System.RuntimeType。
  • 感谢@DangerZone,我使用您的示例解决了问题。我没有修复 2 个返回类型。
  • 部分。 GetType 将返回一个RuntimeType,但typeof() 也返回一个RuntimeType,其中包含有关string[](或System.String[])类型的信息
猜你喜欢
  • 1970-01-01
  • 2022-12-11
  • 2018-08-23
  • 2020-01-20
  • 2020-07-30
  • 1970-01-01
  • 1970-01-01
  • 2022-06-14
  • 2017-08-04
相关资源
最近更新 更多