如何将未知类型的对象传递给函数

Tom*_*mas 1 c# types

是否有可能写入可能会接受一个函数的任何类型object作为参数?

就像是

private bool isItAString(var Input)
{
    string example = "example";
    return Input.GetType() == example.GetType();
}
Run Code Online (Sandbox Code Playgroud)

关键字var无效在这种情况下和它希望它是对象的特定类型。

Dmi*_*nko 6

先说一下问题:

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

由于.Net中的所有对象都是其后代,object我们可以声明Inputas of typeObject并放入

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

或者如果我们想要执行精确检查(我们想要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);
Run Code Online (Sandbox Code Playgroud)

请注意,该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[]  
Run Code Online (Sandbox Code Playgroud)

在你的情况下

   private bool isItAString(var Input)
Run Code Online (Sandbox Code Playgroud)

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