我想测试一个给定的是否object可以转换为给定的Type.
在这种情况下,我有一个对象,并Type表示我想将其强制转换为:
public function FooBar(..., object data, Type expected) {
...
var unboxedData = ?
if (unboxedData == null) {
....
}
...
}
Run Code Online (Sandbox Code Playgroud)
我data该如何转换为类型type代表?
基本上,我想这样做:
var unboxedData = data as Type;
Run Code Online (Sandbox Code Playgroud)
...但当然,你不能使用Type与as语句,所以我该怎么办?
我有一个泛型类,我想强制类型参数的实例始终从String"cast-able"/ convertible.没有例如使用接口可以做到这一点吗?
可能的实施:
public class MyClass<T> where T : IConvertibleFrom<string>, new()
{
public T DoSomethingWith(string s)
{
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
理想的实施:
public class MyClass<T>
{
public T DoSomethingWith(string s)
{
// CanBeConvertedFrom would return true if explicit or implicit cast exists
if(!typeof(T).CanBeConvertedFrom(typeof(String))
{
throw new Exception();
}
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
我更喜欢这种"理想"实现的原因主要是为了不强迫所有Ts实现IConvertibleFrom <>.
我在哪里可以找到转换方法,如
public static implicit operator MyType(OtherType d)
public static implicit operator OtherType(MyType d)
Run Code Online (Sandbox Code Playgroud)
在Type对象?
我有几个PropertyInfo对象代表目标对象的属性。还有一组类似的PropertyInfo对象,它们代表源对象的属性。
如果名称和类型匹配,我的代码将从源向目标分配属性值。但是某些类型是可分配的,但不能完全匹配。一种情况是source属性的类型,Int16但在目标端,同名属性是type的Int32。我使用targetProperty.Type.IsAssignableFrom(sourceProperty.Type)。
换句话说,当我真的希望它给我一个“ true”时,以下返回false
typeof(Int32).IsAssignableFrom(typeof(Int16))
Run Code Online (Sandbox Code Playgroud)
我读过其他线程,它们提示我IsAssignableFrom不是我所需要的。在继续编写冗长的开关案例代码之前,我正在检查是否有更简单的方法。