加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将泛型类型参数转换为数组

发布时间:2020-12-16 00:07:19 所属栏目:百科 来源:网络整理
导读:如果我知道某个泛型类型参数是一个数组,我该如何将其转换为数组或IEnumerable,以便我可以看到它的项目?对于例如 public class FooT{ public T Value { get; set; } public void Print() { if (Value.GetType().IsArray) foreach (var item in Value /*How d
如果我知道某个泛型类型参数是一个数组,我该如何将其转换为数组或IEnumerable,以便我可以看到它的项目?对于例如

public class Foo<T>
{
  public T Value { get; set; }

  public void Print()
  {
    if (Value.GetType().IsArray)
      foreach (var item in Value /*How do I cast this to Array or IEnumerable*/)
        Console.WriteLine(item);
  }
}

解决方法

尝试这样的事情:

public void Print()
{
    var array = Value as Array;
    if (array != null)
        foreach (var item in array)
            Console.WriteLine(item);
}

as关键字:

The as operator is like a cast operation. However,if the conversion isn’t possible,as returns null instead of raising an exception.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读