开发者

Revisiting passing type as parameter

Without generics, I'd like to pass a type as a function parameter without instantiating the type. The handling function should be able to restrict the type, such as (using System.Enum as an example, could be any type though):

enum QuestionType开发者_Python百科s { Great, Good, Huh, Dumb, Dumber }
// error - "QuestionTypes is a type but used like a variable"
static void Main(string[] args) { TypeHandler(QuestionTypes); }
static void TypeHandler(System.Enum enumType) { /* do stuff */ }

This is not the same as passing the type name, a string, or an instance. It seems reasonable that .NET should be able to pass a type, since the definition exists in compiled code. Is this a job only for reflection, or can it be done without?


So....pass a Type parameter?

static void MyFunction(Type t)
{
  ...
}

MyFunction(typeof(QuestionTypes));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜