how create a generic method that can initialize value variable to 0 or ref variable to new (not null)
I have something like this
V Func<V>()
{
// do stuff
V res = default(V);
// more stuff
return res;
}
The problem is that I want res to be either 0 or a new instance of V
I tried creating 2 methods
Func<V> where T: new()
Func<V> where T: struct
but surprisingly this is not allowed
My workaround is to have 2 functions
Fu开发者_如何学CncNew<V> where T: new()
...
res = new V();
....
and
FuncDefault<V> where T: struct
...
res = default(V)
...
EDIT: Summarize answers
new(T) will new up a ref or value type; I did not realize that
You can use the new()
constraint:
private V Func<V>() where V : new()
{
// do stuff
V res = new V();
// more stuff
return res;
}
Value types will be initialized to all-zeros, and any reference types will be initialized using their no-args default constructor.
If the reference type doesn't have a no-args constructor it can't be used with this method, and you'll have to use other ways (there are plenty of solutions to this problem elsewhere on SO, eg Passing arguments to C# generic new() of templated type)
So you want the result object to be integer zero, or a new instance of your generic type? That's not possible because the generic type parameter would only be valid for the integer type unless you specify object
as the return type.
public object Func<T>()
where T: new()
{
if(something)
return 0;
return new T();
}
If you're trying to make a default initializer, you just need to new up the type. This should work for both integer and reference types.
public T Func<T>()
{
return Activator.CreateInstance<T>();
}
精彩评论