Program.cs

164 lines | 4.421 kB Blame History Raw Download
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Reflection;

namespace CreatingAttributes
{
    class Program
    {
        #region Attribute
        // Создаем атрибут
        [AttributeUsage(AttributeTargets.Property)]
        public sealed class MyAttribute : System.Attribute
        {
            public bool ShowPropery { private set; get; }

            public MyAttribute() { }
            public MyAttribute(bool ShowPropery)
            {
                this.ShowPropery = ShowPropery;
            }
        }
        #endregion


        #region UseClass

        class Entity_A
        {
            [MyAttribute(true)]
            public string Name { set; get; }
            [MyAttribute(true)]
            public int Age { set; get; }

            [MyAttribute(false)]
            public string MyType
            {
                get
                {
                    return typeof(Entity_A).Name;
                }
            }
        }
        class Entity_B
        {
            [MyAttribute(false)]
            public string Name { set; get; }
            [MyAttribute(true)]
            public int Age { set; get; }

            [MyAttribute(true)]
            public string MyType
            {
                get
                {
                    return typeof(Entity_B).Name;
                }
            }
        }
        class Entity_С
        {
            public string Name { set; get; }
            public int Age { set; get; }

            public string MyType
            {
                get
                {
                    return typeof(Entity_С).Name;
                }
            }
        }

        #endregion

        #region Logic

        //Вызывает метод демонстрации для массива
        static void PrintProperties(object[] objs)
        {
            foreach (var elem in objs)
                PrintProperties(elem);
        }
        //Метод демострации работы со свойствами и атрибутами
        static void PrintProperties(object obj, bool If_NoAttr = true)
        {
            //Тип объекта
            Type type = obj.GetType();

            //Список свойст обекта
            PropertyInfo[] propertyInfo = type.GetProperties();

            //Строка для вывода результата
            string ObjectProperties = "";

            foreach (var elem in propertyInfo)
            {
                bool PropertyPrint = false;

                //Получить свой атрибут
                MyAttribute myAttribute = elem.GetCustomAttribute<MyAttribute>();

                //Если у свойства есть данный аттрибут
                if (myAttribute != null)
                {
                    //Использовать значение из атрибута
                    if (myAttribute.ShowPropery)
                    {
                        ObjectProperties += $"<HaveAttrubute> {elem.Name}: {elem.GetValue(obj)}";
                        PropertyPrint = true;
                    }
                }
                //Иначе (атрибута нет) использовать флаг из параметра
                else if (If_NoAttr)
                {
                    ObjectProperties += $"{elem.Name}: {elem.GetValue(obj)}";
                    PropertyPrint = true;
                }

                //Вывод разделителя
                if (propertyInfo.Last() != elem && PropertyPrint)
                    ObjectProperties += ", ";
            }

            if (ObjectProperties != "")
                Console.WriteLine(ObjectProperties);
        }

        #endregion


        #region Main
        static void Main(string[] args)
        {
            Entity_A entity_A = new Entity_A
            {
                Name = "Im A",
                Age = 10
            };
            Entity_B entity_B = new Entity_B
            {
                Name = "Im B",
                Age = 20
            };
            Entity_С entity_С = new Entity_С
            {
                Name = "Im С",
                Age = 30
            };

            object[] objs = new object[]
            {entity_A, entity_B, entity_С };

            PrintProperties(objs);

            Console.ReadKey();
        }
        #endregion
    }
}