如何指定默认类型以创建可选的类型参数?

时间:2012-12-05 22:38:22

标签: c# types parameters default optional

我可以解决这个问题,但我很好奇为什么它不起作用:

就像你可以用一个例程的默认值创建一个可选参数一样,例如下面那个......

    public void SomeRoutine(string Title = "Missing")
    {
        // Do something with Title
    }

....为什么不能将默认类型指定为可选参数?

以下示例给出了错误:“'theType'的默认参数必须是编译时常量。”

    public void SomeOtherRoutine(Type theType = typeof(MyClass))
    {
        // Do something based on theType
    }

实际应用程序试图提供枚举包含基类和各种派生类的集合的选项,并仅返回感兴趣的类类型:

    public IEnumerable<MyBaseClass> EnumerateWithOptions(Type optionalDerivedClass = typeof(MyBaseClass))
    {
        foreach (MyBaseClass thingy in MyCustomCollection())
        {
            if (thingy.GetType() == optionalDerivedClass)
            { yield return thingy; };
        }
    }

显而易见的替代方法是重载例程以应用默认值,如下所示,但是由于不值得尝试描述的原因,它在我的应用程序中并不理想。

    public IEnumerable<MyBaseClass> EnumerateWithOptions()
    {
        return EnumerateWithOptions(typeof(MyBaseClass));
    }
    public IEnumerable<MyBaseClass> EnumerateWithOptions(Type optionalDerivedClass)
    {
        foreach (MyBaseClass thingy in MyCustomCollection())
        {
            if (thingy.GetType() == optionalDerivedClass)
            { yield return thingy; };
        }
    }

为什么typeof(MyClass)不被视为编译时常量或任何不同方法的想法?感谢。

2 个答案:

答案 0 :(得分:1)

因此,您无法使用typeof或某些Type值,并且您不希望手动创建过载,请考虑提供null作为可选参数的默认值:

IEnumerable<MyBaseClass> EnumerateWithOptions(Type optionalDerivedClass = null)
{
    if (optionalDerivedClass == null)
        return MyCustomCollection();

    return MyCustomCollection()
        .Where(thingy => thingy.GetType() == optionalDerivedClass);
}

如果您可以使用通用参数而不是Type对象,则可以通过Enumerable.OfType<T>()过滤收集:

IEnumerable<MyBaseClass> result = MyCustomCollection().OfType<YourType>();

答案 1 :(得分:0)

你可以做这样的事情

  public IEnumerable<MyBaseClass> EnumerateWithOptions<T>()
  {
      foreach (MyBaseClass thingy in MyCustomCollection())
      {
         if (thingy.GetType() == typeof(T))
         { yield return thingy; };
      }
  }

使用

var list = EnumerateWithOptions<MyBaseClass>();
var list = EnumerateWithOptions<MyDerivedClass>();