How to pass a Class as parameter for a method? [duplicate]

☆樱花仙子☆ 提交于 2019-12-18 06:14:07

问题


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?

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.


回答1:


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

example:

object instance = Activator.Create(className);

Or like this:

Type type = typeof(MyClass);

MyClass instance = (MyClass)Activator.Create(type);

or in your case:

public void ClassGet(string MyClassName,string blabla)
{
    object instance = Activator.Create(MyClassName);
}

// Call it like:

Gold g = new Gold();
g.ClassGet("MyClass", "blabla");



回答2:


Are you looking for type parameters?

Example:

    public void ClassGet<T>(string blabla) where T : new()
    {
        var myClass = new T();
        //Do something with blablah
    }



回答3:


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:

public void ClassGet<MyClassName>(string blabla) where MyClassName : new() {
  MyClassName NewInstance = new MyClassName();
}



回答4:


 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

            }

        }


来源:https://stackoverflow.com/questions/18806579/how-to-pass-a-class-as-parameter-for-a-method

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