Type t = typeof(int?); //will get this dynamically
object val = 5; //will get this dynamically
object nVal = Convert.ChangeType(val, t);//getting exception here
Run Code Online (Sandbox Code Playgroud)
我在上面的代码中得到了InvalidCastException.对于上面我可以简单地写int? nVal = val,但上面的代码是动态执行.
我得到一个包含在一个对象(这里是val)中的值(非可空类型,如int,float等),我必须通过将它转换为另一个类型(可以是或不可以为空的版本)将其保存到另一个对象它).什么时候
从'System.Int32'到'System.Nullable`1 [[System.Int32,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]'的无效演员表.
一个int,应该是可兑换的/可浇铸的nullable int,这里有什么问题?
目前,我有这种方法来比较两个数字
Private Function ETForGreaterThan(ByVal query As IQueryable(Of T), ByVal propertyValue As Object, ByVal propertyInfo As PropertyInfo) As IQueryable(Of T)
Dim e As ParameterExpression = Expression.Parameter(GetType(T), "e")
Dim m As MemberExpression = Expression.MakeMemberAccess(e, propertyInfo)
Dim c As ConstantExpression = Expression.Constant(propertyValue, propertyValue.GetType())
Dim b As BinaryExpression = Expression.GreaterThan(m, c)
Dim lambda As Expression(Of Func(Of T, Boolean)) = Expression.Lambda(Of Func(Of T, Boolean))(b, e)
Return query.Where(lambda)
End Function
Run Code Online (Sandbox Code Playgroud)
它工作正常,并以这种方式消费
query = ETForGreaterThan(query, Value, propertyInfo)
Run Code Online (Sandbox Code Playgroud)
如您所见,我给它一个IQueryable集合,并根据属性和值为它添加一个where子句.Y可以构造Lessthan,LessOrEqualThan等等System.Linq.Expressions.Expression预定义此运算符.
¿如何转换此代码以对字符串执行相同操作?System.Linq.Expressions.Expression不给我一个预定义的运算符,如"contains"或"startwith",我真的是表达树的noob.
谢谢,请在C#/ VB中发布您的答案.选择让您感觉更舒适的那个.