Object reference not set to an instance of an obje

2019-05-26 10:13发布

I have a console aplication where I am trying to obtain the values of the properties of an object dynamically:

  class Program
  {
    static void Main(string[] args)
    {
      DtoCartaCompromiso test = new DtoCartaCompromiso() { CodProducto = 1,
        DescProducto = "aaa",
        CodProveedor = 2,
        DescProveedor = "bbb",
        FechaExpiracion = DateTime.Now,
        FechaMaxEntrega = DateTime.Now,
        NumLote = "22" };

      var testlist = new List<DtoCartaCompromiso>();
      testlist.Add(test);

      List<Header> columns = new List<Header>() { new Header{Name= "CodProducto"},new Header{Name=  "NumLote"},new Header{Name=  "DescProducto"},new Header{Name=  "CodProveedor"},new Header{Name=  "DescProveedor"},new Header{Name=  "FechaExpiracion"},new Header{Name=  "FechaExpiracion"},new Header{Name=  "FechaMaxEntrega"} };

      foreach (var d in testlist)
      {
        foreach (var col in columns)
        {
            string value = ((d.GetType().GetProperty(col.Name).GetValue(d, null)) ?? "").ToString();
            Console.WriteLine(value);
        }
      }
      Console.Read();    
    }
  }

  public class DtoCartaCompromiso
  {
    public int CodProducto;
    public string NumLote;
    public string DescProducto;
    public int CodProveedor;
    public string DescProveedor;
    public Nullable<DateTime> FechaExpiracion;
    public Nullable<DateTime> FechaMaxEntrega;
  }

  public class Header
  {
      public string Name;
  }

i am getting the error "Object reference not set to an instance of an object" when I get to the line:

string value = ((d.GetType().GetProperty(col.Name).GetValue(d, null)) ?? "").ToString();

the error seems to occur when I get to the GetProperty() method, but I dont understand why

标签: c# reflection
3条回答
爷的心禁止访问
2楼-- · 2019-05-26 10:54

Your property is probably not public. Make it public or pass System.Reflection.BindingFlags.NonPublic to your GetProperty call.

More info: http://msdn.microsoft.com/en-us/library/zy0d4103(v=vs.110).aspx

查看更多
We Are One
3楼-- · 2019-05-26 11:07

Best guess without knowing more about your application, is the following sub-exression results in null:

d.GetType().GetProperty(col.Name)

At that point, the subsequent .GetValue() call will fail with your reported error.

查看更多
霸刀☆藐视天下
4楼-- · 2019-05-26 11:10

The problem is that you don't have properties there in your classes, they are public fields really. A public property looks like

public string PropertyName { get; set; }

but in your case there is lack of both getters and setters.

Change GetProperty() to GetField() and it will work. Or make your fields properties. Personally, I would go with the second option since it is a better idea to use properties instead of public fields.

查看更多
登录 后发表回答