Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Last active November 11, 2025 13:51
Show Gist options
  • Select an option

  • Save sunmeat/b80ace7669e4b55eb54db7c7dfe58983 to your computer and use it in GitHub Desktop.

Select an option

Save sunmeat/b80ace7669e4b55eb54db7c7dfe58983 to your computer and use it in GitHub Desktop.
створення власного атрибуту
using System.Text;
using System.Reflection;
namespace Attributes
{
class Program
{
static void Main()
{
Console.OutputEncoding = Encoding.UTF8;
Test();
AttributeTester.CheckAttribute();
AuthorChecker.CheckAuthors();
}
[Obsolete("цей метод застарілий і його слід уникати")]
static void Test()
{
Console.WriteLine("викликано застарілий метод");
}
}
class AlexAttribute : Attribute
{
// створюємо власний атрибут, успадковуючи від стандартного класу
public int Count { get; set; }
// можна описати кілька властивостей, але для прикладу створюється лише одна
}
[AlexAttribute(Count = 3)]
// використання власного атрибута
class AttributeTester
{
public static void CheckAttribute()
{
Type info = typeof(AttributeTester);
// отримання опису типу
if (Attribute.IsDefined(info, typeof(AlexAttribute)))
// перевірка на існування атрибута
{
var attributeValue = Attribute.GetCustomAttribute(info, typeof(AlexAttribute)) as AlexAttribute;
// отримання значення атрибута
Console.WriteLine($"значення атрибута: {attributeValue.Count}");
// використання значення атрибута для формування результату
}
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true)]
// кілька атрибутів одного типу можна застосовувати до класу
class Author : Attribute
{
public string? name;
public double version;
public Author(string name)
{
this.name = name;
version = 1.0;
}
}
[Author("Dennis Ritchi", version = 1.1)]
[Author("Ken Tompson", version = 1.2)]
class CLanguage
{
// тут все що завгодно
}
class AuthorChecker
{
public static void CheckAuthors()
{
Type type = typeof(CLanguage);
var authors = Attribute.GetCustomAttributes(type, typeof(Author)) as Author[];
foreach (var author in authors)
{
Console.WriteLine($"автор: {author.name}, версія: {author.version}");
}
}
}
}
// !!!!!!!!!!!!!! нижче є ще один приклад !!!!!!!!!!!!!!
// VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
using System.Text;
using System.Reflection;
namespace Attributes
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)]
class AgeAttribute : Attribute
{
// створюємо власний атрибут, успадковуючи від стандартного класу
public int BirthYear { get; set; }
}
class Customer
{
}
[AgeAttribute(BirthYear = 1989)]
class AdultCustomer : Customer
{
}
// [AgeAttribute(BirthYear = DateTime.Now.Year - 15)] // error
[AgeAttribute(BirthYear = 2010)]
class YoungCustomer : Customer
{
}
class Seller
{
public void SellBeer(Customer c)
{
var attributes = c.GetType().GetCustomAttributes(typeof(AgeAttribute), false);
if (attributes.Length > 0)
{
var attr = (AgeAttribute)attributes[0];
if (attr.BirthYear >= 2007)
{
Console.WriteLine("вибачте, ви надто молоді");
}
else
{
Console.WriteLine("ось ваше пиво");
}
}
else
{
Console.WriteLine("вибачте! покажіть паспорт!");
}
}
}
class Program
{
static void Main()
{
Console.OutputEncoding = Encoding.UTF8;
var seller = new Seller();
var alex = new AdultCustomer();
seller.SellBeer(alex);
var kid = new YoungCustomer();
seller.SellBeer(kid);
var someone = new Customer();
seller.SellBeer(someone);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment