[英]Switching on type in C# with no instance of the type
I have a generic base class for a WPF UserControl. 我有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. 我将
default(T)
写入default(T)
值的地方,我意识到我真正想要的是不同的东西。 For reference types the default(T)
is null which is not what I want in this special case. 对于引用类型,
default(T)
为null,在这种特殊情况下,这不是我想要的。 I would like to build a custom default
operator if possible that allows me to return my own idea of what default should be. 如果可能,我想构建一个自定义的
default
运算符,该运算符使我可以返回自己的默认值。 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#. 在C ++中,我将使用traits类来获取此信息,但我认为这在C#中是不可能的。 In C++ I would end up doing something like.
在C ++中,我最终会做类似的事情。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.