Skip to main content
 首页 » 编程设计

c#之通过匹配其属性来填充类

2024年02月23日26sharpest

所以我有一个导入的文件。基本上,我想使用这个文件的标题来知道哪些列应该放在我的类的哪个变量值中。我想通过 C# 中的变量属性进行比较,但我不确定如何处理和设置它。

例如,假设我的类中的一个变量是 public string Name;,而在导入的文件中,列标题之一是 Name。我宁愿不使用反射来直接匹配变量。如何在我的类变量上设置一个属性,然后使用它来匹配这些本地 string header 变量,并填充正确的?

请您参考如下方法:

这是一个示例程序,可以满足您的需求。 SetOption 方法提供反射逻辑以查找具有指定选项名称的字段并设置其值。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Reflection; 
 
namespace ConsoleApplication1 
{ 
   // This is the attribute that we will apply to the fields 
   // for which we want to specify an option name. 
   [AttributeUsage(AttributeTargets.Field)] 
   public class OptionNameAttribute : Attribute 
   { 
      public OptionNameAttribute(string optionName) 
      { 
         OptionName = optionName; 
      } 
 
      public string OptionName { get; private set; } 
   } 
 
   // This is the class which will contain the option values that  
   // we read from the file. 
   public class OptionContainer 
   { 
      [OptionName("Name")] 
      public string MyNameField; 
 
      [OptionName("Value")] 
      public string MyValueField; 
   } 
 
   class Program 
   { 
      // SetOption is the method that assigns the value provided to the  
      // field of the specified instance with an OptionName attribute containing 
      // the specified optionName. 
      static void SetOption(object instance, string optionName, string optionValue) 
      { 
         // Get all the fields that has the OptionNameAttribute defined 
         IEnumerable<FieldInfo> optionFields = instance.GetType() 
            .GetFields() 
            .Where(field => field.IsDefined(typeof(OptionNameAttribute), true)); 
 
         // Find the single field where the OptionNameAttribute.OptionName property 
         // matches the provided optionName argument. 
         FieldInfo optionField = optionFields.SingleOrDefault(field => 
            field.GetCustomAttributes(typeof(OptionNameAttribute), true) 
            .Cast<OptionNameAttribute>().Single().OptionName.Equals(optionName)); 
 
         // If the found field is null there is no such option. 
         if (optionField == null) 
            throw new ArgumentException(String.Format("Unknown option {0}", optionName), "optionname"); 
 
         // Finally set the value. 
         optionField.SetValue(instance, optionValue); 
      } 
 
      static void Main(string[] args) 
      { 
         OptionContainer instance = new OptionContainer(); 
         SetOption(instance, "Name", "This is the value of Name"); 
         SetOption(instance, "Value", "This is my value"); 
 
         Console.WriteLine(instance.MyNameField); 
         Console.WriteLine(instance.MyValueField); 
      } 
   } 
}