CreatingAttributes

Демострация работы с свойствами классов. Создание своих атрибутов,

10/12/2018 7:48:14 PM

Details

.gitignore 5(+5 -0)

diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..a5bde8e
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+
+CreatingAttributes/.vs/CreatingAttributes/v15/Server/
+
+CreatingAttributes/CreatingAttributes/bin/
+CreatingAttributes/CreatingAttributes/obj/
diff --git a/CreatingAttributes/.vs/CreatingAttributes/v15/.suo b/CreatingAttributes/.vs/CreatingAttributes/v15/.suo
new file mode 100644
index 0000000..60cbded
Binary files /dev/null and b/CreatingAttributes/.vs/CreatingAttributes/v15/.suo differ
diff --git a/CreatingAttributes/CreatingAttributes.sln b/CreatingAttributes/CreatingAttributes.sln
new file mode 100644
index 0000000..db24e21
--- /dev/null
+++ b/CreatingAttributes/CreatingAttributes.sln
@@ -0,0 +1,25 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 15
+VisualStudioVersion = 15.0.28010.2036
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreatingAttributes", "CreatingAttributes\CreatingAttributes.csproj", "{7CD262E6-3DD1-4DAB-833E-A8558CB67030}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Any CPU = Debug|Any CPU
+		Release|Any CPU = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{7CD262E6-3DD1-4DAB-833E-A8558CB67030}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{7CD262E6-3DD1-4DAB-833E-A8558CB67030}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{7CD262E6-3DD1-4DAB-833E-A8558CB67030}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{7CD262E6-3DD1-4DAB-833E-A8558CB67030}.Release|Any CPU.Build.0 = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+	GlobalSection(ExtensibilityGlobals) = postSolution
+		SolutionGuid = {C88AA72E-8E7C-4A88-8131-797B2CA23101}
+	EndGlobalSection
+EndGlobal
diff --git a/CreatingAttributes/CreatingAttributes/App.config b/CreatingAttributes/CreatingAttributes/App.config
new file mode 100644
index 0000000..8e15646
--- /dev/null
+++ b/CreatingAttributes/CreatingAttributes/App.config
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<configuration>
+    <startup> 
+        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
+    </startup>
+</configuration>
\ No newline at end of file
diff --git a/CreatingAttributes/CreatingAttributes/CreatingAttributes.csproj b/CreatingAttributes/CreatingAttributes/CreatingAttributes.csproj
new file mode 100644
index 0000000..503b677
--- /dev/null
+++ b/CreatingAttributes/CreatingAttributes/CreatingAttributes.csproj
@@ -0,0 +1,52 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{7CD262E6-3DD1-4DAB-833E-A8558CB67030}</ProjectGuid>
+    <OutputType>Exe</OutputType>
+    <RootNamespace>CreatingAttributes</RootNamespace>
+    <AssemblyName>CreatingAttributes</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+    <Deterministic>true</Deterministic>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <PlatformTarget>AnyCPU</PlatformTarget>
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <PlatformTarget>AnyCPU</PlatformTarget>
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+    <Reference Include="System.Xml.Linq" />
+    <Reference Include="System.Data.DataSetExtensions" />
+    <Reference Include="Microsoft.CSharp" />
+    <Reference Include="System.Data" />
+    <Reference Include="System.Net.Http" />
+    <Reference Include="System.Xml" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="Program.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="App.config" />
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+</Project>
\ No newline at end of file
diff --git a/CreatingAttributes/CreatingAttributes/Program.cs b/CreatingAttributes/CreatingAttributes/Program.cs
new file mode 100644
index 0000000..68e095e
--- /dev/null
+++ b/CreatingAttributes/CreatingAttributes/Program.cs
@@ -0,0 +1,163 @@
+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
+    }
+}
diff --git a/CreatingAttributes/CreatingAttributes/Properties/AssemblyInfo.cs b/CreatingAttributes/CreatingAttributes/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..7ce4710
--- /dev/null
+++ b/CreatingAttributes/CreatingAttributes/Properties/AssemblyInfo.cs
@@ -0,0 +1,36 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// Общие сведения об этой сборке предоставляются следующим набором
+// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
+// связанные со сборкой.
+[assembly: AssemblyTitle("CreatingAttributes")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("CreatingAttributes")]
+[assembly: AssemblyCopyright("Copyright ©  2018")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
+// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
+// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
+[assembly: ComVisible(false)]
+
+// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
+[assembly: Guid("7cd262e6-3dd1-4dab-833e-a8558cb67030")]
+
+// Сведения о версии сборки состоят из следующих четырех значений:
+//
+//      Основной номер версии
+//      Дополнительный номер версии
+//   Номер сборки
+//      Редакция
+//
+// Можно задать все значения или принять номер сборки и номер редакции по умолчанию.
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]