PropertyInfo GetValue() Object does not match target type

前端 未结 4 1368
被撕碎了的回忆
被撕碎了的回忆 2021-01-17 15:33

I want to read value of a T type

  public virtual ActionResult Edit(TEditDTO editedDTO)
    {
        if (!ModelState.IsValid) return View(editedDTO);
               


        
相关标签:
4条回答
  • 2021-01-17 15:52

    Try this,

    var Id = prop.GetValue(editedDTO, null);
    
    0 讨论(0)
  • 2021-01-17 16:01

    You should pass the instance of TEditDTO to GetValue method not the type instance.

    var Id = prop.GetValue(editedDTO);
    
    0 讨论(0)
  • 2021-01-17 16:08

    the PropertyInfo.GetValue method accepts as the first argument an instance of the type for which you want to read the value. if using an indexer you also need to specify an additional array argument to GetValue. since both arguments are required you need to pass null for the second one when reading a normal property. in your example you're passing a Type instance instead of a TEditDTO instance. use the code below.

    var Id = prop.GetValue(editedDTO, null);
    
    0 讨论(0)
  • 2021-01-17 16:14

    Try this:

    public virtual ActionResult Edit(TEditDTO editedDTO)
    {
        if (!ModelState.IsValid) return View(editedDTO); 
        PropertyInfo prop = typeof(editedDTO).GetProperty("Id") ;
        Object Id = prop.GetValue(editedDTO); 
    }
    
    0 讨论(0)
提交回复
热议问题