using the 'class' keyword as/in a method argument in c#

纵饮孤独 提交于 2019-12-13 15:44:16

问题


I'm not sure where I saw this, and I'm certainly not getting the syntax past the compiler. Is it possible to use the 'class' C# keyword as part of a method parameter signature?

foo(string x, class y) { }

Anyone else see something like this? thanks, -gene


回答1:


Should you be using object maybe? It looks like you are trying to specify a parameter that can have any type, in which case you should use object, since everything derives from it.




回答2:


I don't think you can use it as in your example, but if you would want to use the word "class" as a parameter name, that is doable by prefixing it with @:

foo(string @class) { }



回答3:


It is possible to use the word class in in a generic method definition:

foo<T>(T object) where T:class



回答4:


Use object if you want to be able to pass y as anything:

foo(string x, class y) { }

use generics if you want to state y has to be an object of a class - not a struct or an internace for example.

foo<MyType>(string x, MyType y) where MyType : class { }


来源:https://stackoverflow.com/questions/1293850/using-the-class-keyword-as-in-a-method-argument-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!