例如:我有 2 个变量(值)和(属性)我想检查是否可以转换为值?我们不知道变量的类型,如何检查是否可以转换?
var value = Reader[item];
PropertyInfo property = properties.Where(x => x.Name == item).FirstOrDefault();
var type=property.PropertyType;//Or property.ReflectedType
var cs= value as type // Error: type is variable but is used like a Type
if (cs!=null){
...
}
示例 1:
var value = 123;//is int
type = property.GetType();// is double
var x = (double)value;//Can be casted
示例 2:
var value = "asd";//is string
type = property.GetType();// is double
var x = (double)value;//Can not be casted
最佳答案
您可以使用 IsAssignable
:
bool isValidCast = type.IsAssignableFrom(value.GetType())
根据关于 int
到 double
的评论:
我在评论中犯了一个错误,所以我删除了它。
int
可以隐式转换为 double
因为有预定义的隐式转换,参见 here
有很多方法可以将类型转换或转换为类型。例如,您可以使用 implicit/explicit conversion , 你可以使用 TypeConverter
或实现 IConvertible
接口(interface)。
现在,您必须决定哪个用例与您相关。检查所有这些可能有点复杂,尤其是在设计时不知道目标类型的情况下。
关于c# - 如何在 as 运算符中使用变量类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47975536/