C# 如何将类作为方法的参数传递?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18806579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass a Class as parameter for a method?
提问by Amin AmiriDarban
I have two classs:
我有两个班级:
Class Gold;
Class Functions;
There is a method ClassGet
in class Functions
, which has 2 parameters.
I want to send the class Gold
as parameter for one of my methods in class Functions
.
How is it possible?
ClassGet
class 中有一个方法Functions
,它有 2 个参数。我想将该类Gold
作为我在 class 中的方法之一的参数发送Functions
。这怎么可能?
For example:
例如:
public void ClassGet(class MyClassName, string blabla)
{
MyClassName NewInstance = new MyClassName();
}
Attention:I want to send MyClassName
as string parameter to my method.
注意:我想MyClassName
作为字符串参数发送到我的方法。
采纳答案by Jeroen van Langen
The function you're trying to implement already exists (a bit different)
您尝试实现的功能已经存在(有点不同)
Look at the Activator class: http://msdn.microsoft.com/en-us/library/system.activator.aspx
查看 Activator 类:http: //msdn.microsoft.com/en-us/library/system.activator.aspx
example:
例子:
private static object CreateByTypeName(string typeName)
{
// scan for the class type
var type = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
from t in assembly.GetTypes()
where t.Name == typeName // you could use the t.FullName aswel
select t).FirstOrDefault();
if (type == null)
throw new InvalidOperationException("Type not found");
return Activator.CreateInstance(type);
}
Usage:
用法:
var myClassInstance = CreateByTypeName("MyClass");
回答by Guffa
You could send it as a parameter of the type Type
, but then you would need to use reflection to create an instance of it. You can use a generic parameter instead:
您可以将它作为 type 的参数发送Type
,但随后您需要使用反射来创建它的实例。您可以改用泛型参数:
public void ClassGet<MyClassName>(string blabla) where MyClassName : new() {
MyClassName NewInstance = new MyClassName();
}
回答by Khan
Are you looking for type parameters?
您在寻找类型参数吗?
Example:
例子:
public void ClassGet<T>(string blabla) where T : new()
{
var myClass = new T();
//Do something with blablah
}
回答by Amin AmiriDarban
public void ClassGet(string Class, List<string> Methodlist)
{
Type ClassType;
switch (Class)
{
case "Gold":
ClassType = typeof(Gold); break;//Declare the type by Class name string
case "Coin":
ClassType = typeof(Coin); break;
default:
ClassType = null;
break;
}
if (ClassType != null)
{
object Instance = Activator.CreateInstance(ClassType); //Create instance from the type
}
}