检测class构造函数中传入的参数类型

Detect the type of parameter passed in class constructor

我希望 class 的构造函数能够传递两种类型的参数,然后在方法内部根据参数的类型做一些事情。类型为 doubleString[]。 class 及其构造函数类似于:

public class MyClass
{
    public MyClass (Type par /* the syntax here is my issue */ )
    {
        if (Type.GetType(par) == String[])
        {  
            /// Do the stuff
        }

        if (Type.GetType(par) == double)
        {  
            /// Do another stuff 
        }
}

并且 class 将以这种方式在另一个 class 上实例化:

double d;
String[] a;

new MyClass(d);    /// or new MyClass(a);

最简单的方法是创建两个构造函数。每种类型一个。

public class MyClass
{
   public MyClass (Double d)
   {
        //stuff
   }

   public MyClass(String[] s)
   {
       //other stuff
   }
}

此外,我建议您阅读这篇文章article

您可以使用以下内容 - 但我不推荐它。从类型安全的角度来看,单独的构造函数(如 所示)会更简单和更好。

public MyClass(object par)
{

    if (par.GetType() == typeof(double))
    {
        // do double stuff
    }
    if (par.GetType() == typeof(string))
    {
        // do string stuff
    }
    else
    {
       // unexpected - fail somehow, i.e. throw ...
    }
}