TheSwamp

Code Red => .NET => Topic started by: gswang on June 01, 2017, 11:48:12 PM

Title: How to determine whether an object has an property?
Post by: gswang on June 01, 2017, 11:48:12 PM
In .NET,How to determine whether an object has an property? like vlax-property-available-p in lisp.
(vlax-property-available-p obj 'Thickness)
Thank you very much!
Title: Re: How to determine whether an object has an attribute?
Post by: Atook on June 02, 2017, 12:09:47 AM
From Autodesk. (https://knowledge.autodesk.com/search-result/caas/CloudHelp/cloudhelp/2015/ENU/AutoCAD-NET/files/GUID-BA69D85A-2AED-43C2-B5B7-73022B5F28F8-htm.html)

You can check the BlockTableRecord for .HasAttributes.

If so, you can access them via the blockreference.AttributeCollection.
Title: Re: How to determine whether an object has an property?
Post by: kdub_nz on June 02, 2017, 12:37:19 AM
Since attribute are attached to blocks ...
(https://i.gyazo.com/a10093196047472711da19dfba85683a.png)
Title: Re: How to determine whether an object has an property?
Post by: gile on June 02, 2017, 01:25:26 AM
Hi,

You can use Reflection:

Code - C#: [Select]
  1. public bool IsAvailableProperty(object obj, string propertyName) =>
  2.     obj.GetType().GetProperties().Any(p => p.Name == propertyName);
Title: Re: How to determine whether an object has an property?
Post by: gswang on June 02, 2017, 08:13:05 AM
Thank you, gile,
but i can't compile successfully, how to use reflection?
Title: Re: How to determine whether an object has an property?
Post by: gile on June 02, 2017, 08:32:42 AM
You have to add a using System.Linq; directive and, if you're not using VS 2015 ou higher (C# 6), change the code as this:

Code - C#: [Select]
  1.         public bool IsAvailableProperty(object obj, string propertyName)
  2.         {
  3.             return obj.GetType().GetProperties().Any(p => p.Name == propertyName);
  4.         }
Title: Re: How to determine whether an object has an property?
Post by: gswang on June 02, 2017, 09:02:01 AM
Thank you very much, gile. I made it successfully! :2funny:
Title: Re: How to determine whether an object has an property?
Post by: Bobby C. Jones on June 05, 2017, 04:08:11 PM
In .NET,How to determine whether an object has an property? like vlax-property-available-p in lisp.
(vlax-property-available-p obj 'Thickness)
Thank you very much!

Nothing against reflection, it can be useful, but it seems in a type safe environment the better question asks if the object implements an interface that declares the desired property or method.