c# - 如何在 as 运算符中使用变量类型

标签 c# casting propertyinfo as-operator

例如:我有 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())

根据关于 intdouble 的评论: 我在评论中犯了一个错误,所以我删除了它。 int 可以隐式转换为 double 因为有预定义的隐式转换,参见 here

有很多方法可以将类型转换或转换为类型。例如,您可以使用 implicit/explicit conversion , 你可以使用 TypeConverter或实现 IConvertible 接口(interface)。

现在,您必须决定哪个用例与您相关。检查所有这些可能有点复杂,尤其是在设计时不知道目标类型的情况下。

关于c# - 如何在 as 运算符中使用变量类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47975536/

相关文章:

mysql - 在mysql中将科学记数法从Varchar转换为Decimal

c# - 将焦点设置到文本框中的按钮?

c# - .Net 4.0 重构现有 "if"条件和 "is"运算符的优化代码

php - PHP 中的内爆与 MySQL 中的内爆 - 哪个使用更少的 cpu?

c# - 在 C# 中转换与转换的适当时间

linq - 使用 linq 查询对象的属性

c# - C# 中的 SQL 连接字符串

c# - 为什么 ReSharper 提示这种 ResourceLoader.GetString 的使用?

.net - 为什么基类的成员与派生类中的相同成员不同?

c# - PropertieInfo 的 GetValue 抛出 TargetParameterCountException (System.Reflection)