【问题标题】:How to pass a Class as parameter for a method? [duplicate]如何将类作为方法的参数传递? [复制]
【发布时间】:2013-09-19 08:06:01
【问题描述】:

我有两个班级:

Class Gold;
Class Functions;

Functions 类中有一个方法ClassGet,它有 2 个参数。 我想发送Gold 类作为Functions 类中我的方法之一的参数。 怎么可能?

例如:

public void ClassGet(class MyClassName, string blabla)
{
    MyClassName NewInstance = new MyClassName();
}

注意:我想将MyClassName 作为字符串参数发送到我的方法。

【问题讨论】:

  • 只需为黄金类创建一个对象并将其作为参数传递给函数。

标签: c# function class methods parameter-passing


【解决方案1】:

您在寻找类型参数吗?

例子:

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

【讨论】:

    【解决方案2】:

    您尝试实现的功能已经存在(有点不同)

    查看 Activator 类:http://msdn.microsoft.com/en-us/library/system.activator.aspx

    示例:

    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 as well
                    select t).FirstOrDefault();
    
        if (type == null)
            throw new InvalidOperationException("Type not found");
    
        return Activator.CreateInstance(type);
    }
    

    用法:

    var myClassInstance = CreateByTypeName("MyClass");
    

    【讨论】:

    • @T.Todua 你是对的。我会更新的。
    【解决方案3】:

    您可以将它作为Type 类型的参数发送,但是您需要使用反射来创建它的实例。您可以改用泛型参数:

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

    【讨论】:

    • 错误答案...我想将我的类名作为字符串作为参数发送给我的方法
    • 作为字符串?这绝对不是你要求的......所以,错误的问题。 ;) 然后您将使用 Activator.CreateInstance(typestr, false) 方法从该字符串创建一个实例。
    【解决方案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
    
                }
    
            }
    

    【讨论】:

      猜你喜欢
      • 2018-03-02
      • 2012-01-11
      • 2015-01-22
      • 2012-09-18
      • 1970-01-01
      • 1970-01-01
      • 2021-05-19
      • 2021-09-10
      • 1970-01-01
      相关资源
      最近更新 更多