I have a generic base class for a WPF UserControl. One of the dependency properties is defined as
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register
( "Value"
, typeof(T)
, typeof(ValidatingTextBox<T,C>)
, new FrameworkPropertyMetadata(default(T), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)
);
where I write default(T)
for the default value I realize that what I really want is something different. For reference types the default(T)
is null which is not what I want in this special case. I would like to build a custom default
operator if possible that allows me to return my own idea of what default should be. Is this possible?
For example I imagine
public static T MyDefault<T>(){
switch(typeof(T)){
case (typeof(String)) : return "";
case (typeof(Foo)) : return new Foo();
}
}
obviously the above will not compile for many reasons but the intent should be clear. Is there a way to do this?
In C++ I would use traits classes to get this but I don't think that is possible in C#. In C++ I would end up doing something like.
DefaultGenerator<T>.Default
Something like this?
private static Dictionary<Type,Func<object>> factory = new Dictionary<Type,Func<object>>{
{typeof(string), ()=> String.Empty },
{typeof(MyClass), ()=> new MyClass() },
};
public static T MyDefault<T>()
{
Type t = typeof(T);
Func<object> func = null;
if(factory.TryGetValue(t, out func))
return (T)func();
else
return default(T);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.