This article shows the implementation method of C# using reflection to determine whether an object contains a certain attribute, which has certain learning value for C# programmers.
The specific implementation code is as follows:
/// <summary> /// Use reflection to determine whether an object contains a certain attribute/// </summary> /// <param name="instance">object</param> /// <param name="propertyName">Properties that need to be judged</param>/// <returns> Whether to include</returns>public static bool ContainProperty(this object instance, string propertyName) { if (instance != null && !(propertyName)) { PropertyInfo _findedPropertyInfo = ().GetProperty(propertyName); return (_findedPropertyInfo != null); } return false; }
The code usage method is as follows:
bool cc = _person.ContainProperty("cc"); bool aa = _person.ContainProperty("Age");
I hope the examples described in this article can be helpful to everyone!