首页 > 解决方案 > 如何将未知类型的对象传递给函数

问题描述

是否可以编写一个接受任何类型作为object参数的函数?

就像是

private bool isItAString(var Input)
{
    string example = "example";
    return Input.GetType() == example.GetType();
}

关键字在此实例var无效,并且它希望它是特定类型的对象。

标签: c#types

解决方案


首先说明问题:

给定任意Input类型的对象,如果它是一个我们应该返回string

由于.Net中的所有对象都是我们的后代,object因此我们可以声明Input为类型Object并放入

  // means you can put string value = Input;
  // and value will be assigned  
  private static bool isItAString(object Input) => 
    Input is string;

或者如果我们想要执行精确检查(我们想要Input类型string而不是别的)

  // Or ... => Input == null || ...
  // if we accept null as a valid string 
  private static bool isItAString(object Input) => 
    Input != null && Input.GetType() == typeof(string);

请注意,该var关键字表示类型推断:我们要求 .net推断所需的类型,而不是明确输入:

  // data is of type string[] 
  var data = new List<int>() {1, 2, 3} // List<int>
    .Select(x => x.ToString())         // IEnumerable<string>
    .OrderBy(x => x)                   // IOrderedEnumerable<string>
    .ToArray();                        // string[]  

在你的情况下

   private bool isItAString(var Input)

.Net 无法推断实际Input类型(是objectstring??)


推荐阅读