这个模式有名字吗?(C#编译时类型安全与"params"不同类型的args)

Edw*_*uff 19 c# params type-safety

这个模式有名字吗?

假设您要创建一个采用可变数量参数的方法,每个参数必须是一组固定类型(以任何顺序或组合),以及您无法控制的某些类型.一种常见的方法是让您的方法接受Object类型的参数,并在运行时验证类型:

void MyMethod (params object[] args)
{
    foreach (object arg in args)
    {
        if (arg is SomeType)
            DoSomethingWith((SomeType) arg);
        else if (arg is SomeOtherType)
            DoSomethingElseWith((SomeOtherType) arg);
        // ... etc.
        else throw new Exception("bogus arg");
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,让我们说,像我一样,你沉迷于编译时类型安全性,并希望能够在编译时验证方法的参数类型.这是我想出的一种方法:

void MyMethod (params MyArg[] args)
{
    // ... etc.
}

struct MyArg
{
    public readonly object TheRealArg;

    private MyArg (object obj) { this.TheRealArg = obj; }

    // For each type (represented below by "GoodType") that you want your 
    // method to accept, define an implicit cast operator as follows:

    static public implicit operator MyArg (GoodType x)
    { return new MyArg(x); }

}
Run Code Online (Sandbox Code Playgroud)

隐式转换允许您将有效类型的参数直接传递给例程,而无需显式转换或包装它们.如果尝试传递不可接受类型的值,则会在编译时捕获该错误.

我确定其他人已经使用过这种方法,所以我想知道这种模式是否有名称.

Jon*_*son 0

这看起来像是复合模式的一个子集。引用维基百科:

复合模式描述了一组对象的处理方式与对象的单个实例相同。