【问题标题】:Detect the type of parameter passed in class constructor检测类构造函数中传递的参数类型
【发布时间】:2015-10-24 07:33:58
【问题描述】:

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

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 
        }
}

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

double d;
String[] a;

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

【问题讨论】:

  • 只需重载构造函数并从两者调用初始化方法。
  • 我怀疑你想要if (type == typeof(string[]))...你只想要类型,对吧,而不是类型的instance
  • @Aggressor 谢谢。这是正确的方式
  • @JonSkeet 我认为你是对的,但你能再解释一下吗?
  • 那么您还需要什么解释? (不清楚你是否真的只需要按类型做事,或者你是否真的应该采用类型的 instances...)

标签: c# class types constructor parameter-passing


【解决方案1】:

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

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

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

另外,我建议您阅读此article

【讨论】:

    【解决方案2】:

    您可以使用以下内容 - 但我不建议您这样做。从类型安全的角度来看,单独的构造函数(如 the other answer 所示)会更简单且更好。

    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 ...
        }
    }
    

    【讨论】:

    • 如果有人将它与任何其他类型一起使用怎么办?
    • 这就是为什么这是一个坏主意。为什么你希望他们能够发送任何东西?使用 if ... else if .. 如果您不知道对象是什么,最后一个 else 将是做什么。但如果你只想要双精度或字符串.. 2 个构造函数更好
    • 问题不是如果他们通过了其他类型会发生什么,问题是想要发生什么我>。这就是为什么重载构造函数是一个更好的解决方案。它们指示允许的内容并允许您编写简洁的代码。
    • 提及另一种方法并在 cmets 中展示其优缺点很有帮助。谢谢。
    • 旁注:par.GetType() == typeof(double) 可以缩短为par is double。整洁一点!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    相关资源
    最近更新 更多