C# custom attribute get interface implementation example code

Time:2021-7-31

General interface implementation polymorphism

Define interface


 interface Ipeople
 {
  void say();
 }

Define implemented classes


 public class man : Ipeople
 {
  public void say()
  {
   MessageBox.Show("man");
  }
 }

 public class woman : Ipeople
 {
  public void say()
  {
   MessageBox.Show("woman");
  }
 }

General implementation method

Upgrade

Add custom (there are many online)

Implementation class

Call method


 private static void NewMethod(string tpye)
  {
   Ipeople ib = null;
   var types = AppDomain.CurrentDomain.GetAssemblies()
      .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(Ipeople))))
      .ToArray();
   foreach (var v in types)
   {
    var attribute = v.GetCustomAttributes(typeof(NameAttribute), false).FirstOrDefault();
    if (attribute != null && ((NameAttribute)attribute).Name == tpye)
    {
     ib = (Ipeople)v.Assembly.CreateInstance(v.FullName);
     break;
    }
   }
   if (ib != null) ib.say();
  }

This avoids the need to maintain swich statements

summary

The above is the whole content of this article. I hope the content of this article has certain reference and learning value for your study or work. Thank you for your support for developpaer.

Recommended Today

An example of using builder pattern in Ruby design pattern programming

Let’s review it firstDesign patternBasic concepts of: definitionSeparate the construction of a complex object from its representation, so that the same construction process can create different representations.The builder hides how the product is assembled, so if you need to change the internal representation of a product, you only need to redefine a builder. Practical scope1. […]