问题
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