问题描述
我想要做的是:
bool Convert( out Object output, Object source)
{
// find type of output.
// convert source to that type if possible
// store result in output.
return success
}
这可能吗?
Is it possible?
显然,有一个蛮力巨大的if结构,可以工作,但这需要写一个if块每一个可以想象的数据类型。即使假设我们将其限制为原语和字符串,它仍然是code一大块。我想的东西多一点反思。
Obviously, there is a brute force massive "if" construct that could work, but that would require writing an if block for every conceivable data type. Even assuming we'll limit it to primitives and strings, it's still a huge chunk of code. I'm thinking about something a bit more reflective.
旁白:虽然经历了API,我遇到了Convert.IsDBNull()方法,这将节省我很多
Aside: While going through the api, I came across the Convert.IsDBNull() method, which will save me a lot of
if ( !databasefield.GetType().Equals( DBNull.Value ) )
为什么在G-D的名字是它的转换?为什么不DBNull.IsDBNull()?
Why in the name of G-d is it in Convert? Why not DBNull.IsDBNull() ?
推荐答案
没有神圣的转换法宝。对于M型则需要M *(M-1)转换例程来覆盖所有的排列。
There is no holy grail of conversion. For m types you would need m*(m-1) conversion routines to cover all the permutations.
有关原始类型,用Convert.ChangeType
For primitive types, use Convert.ChangeType
如果一个类型是可转换到从一个原始的,它可以实现IConvertable接口,并从转换类使用。
If a type is convertable to-from a primitive, it can implement the IConvertable interface and be used from the Convert class.
对于一切,@布赖恩Rudolfs的回答是最好的。注册您需要每个排列一个明确的转换方法。
For everything else, @Brian Rudolfs answer is the best. Register an explicit conversion method for each permutation you require.
这篇关于如何使一个通用型的转换方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!