Create an instance of a class from an instance of the type of its generic parameter
I want to do this:
public class ValueContainer<T> {
public T Value { get; set; }
}
Then I want to assign a value to it like this:
private ValueContainer<string> value;
value = "hello";
I'm sure I've seen this somewhere but can't figure out how 开发者_Python百科to do it.
TIA
You can use a custom implicit operator, e.g:
public static implicit operator ValueContainer<T>(T value) {
return new ValueContainer { Value = value };
}
While this is a nice language feature of C#, it is not CLS compliant and won't be supported by other .NET languages like VB.NET, so if you are designing types to be reused with other languages, its worth baring that in mind.
Creating your own implicit operator will take care of this problem.
class Program
{
static void Main(string[] args)
{
Container<string> container;
container = "hello";
}
}
public class Container<T>
{
public T Value { get; set; }
public static implicit operator Container<T>(T val)
{
return new Container<T> { Value = val };
}
}
精彩评论