私はこれを回避することができますが、なぜそれがうまくいかないのか興味があります:
以下のようなルーチンのデフォルト値を持つオプションのパラメータを作成できるのと同じ方法で.....
public void SomeRoutine(string Title = "Missing")
{
// Do something with Title
}
.... デフォルトの Type をオプションのパラメータとして割り当てられないのはなぜですか?
次の例では、 「'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) がコンパイル時定数と見なされない理由、または別のアプローチのアイデアはありますか? ありがとう。