Create a object in C# without the use of new Keyword? [closed]

妖精的绣舞 提交于 2020-07-05 07:37:09

问题


Is there a way to create a object without the use of new keyword in C# some thing like class.forname(); in java.

I want to dynamically create a object of a class. The object creation may depend on the users input.
I have a base class x and there are 5 subclasses (a,b,c,d,e) of it. My user input will be a or b or...e class names. Using this I need to create a object of that class.How do I do this


回答1:


you can use the Activator class.

Type type = typeof(MyClass);
object[] parameters = new object[]{1, "hello", "world" };
object obj = Activator.CreateInstance(type, parameters);
MyClass myClass = obj as MyClass;



回答2:


Do you mean a static class?

static class Foo
{
    public static void Bar()
    {
        Console.WriteLine("Foo.Bar()");
    }
}

You can then call Foo.Bar();.

But you'd better explain what you're trying to do. "Creating an object without the use of new" is a solution you came up with for a problem you're having. Just explaining that problem might reveal an easier way to solve it.

Edit: you seem to need a factory, given your comment "I want to dynamically create a object of a class. The object creation may depend on the users input".

So something like this may be sufficient:

static class PizzaFactory
{
    static Pizza CreatePizza(String topping)
    {
        if (topping == "cheese")
        {
            return new CheesePizza();
        }
        else if (topping == "salami")
        {
            return new SalamiPizza();
        }
    }
}

class Pizza { }
class CheesePizza : Pizza { }
class SalamiPizza : Pizza { }

Throwing in an Interface or Abstract class where necessary.




回答3:


Activator class is very slow you can use the lambda expressions look at this Activator alternative




回答4:


You can use the default keyword, but it will only result in an instance for value types:

var s = default(string); // null
var i = default(int);    // integer (0)



回答5:


You may be able to do it with

typeof(MyType)


来源:https://stackoverflow.com/questions/8049193/create-a-object-in-c-sharp-without-the-use-of-new-keyword

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