从C#接口的属性获取多个实现类中字段的值
private List<string> GetImplName() { List<string> ls = new List<string>(); var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IBaseContainer)))) .ToArray(); foreach (var v in types) { object ct = Activator.CreateInstance(v); string name = (string)v.GetProperty("Name").GetValue(ct, null); ls.Add($"{name}"); } return ls; }
public interface IBaseContainer { /// <summary> /// 类型名字,属性访问器,访问实现类中的_name字段 /// </summary> string Name { get; } /// <summary> /// 数据保存 /// </summary> void Save(); /// <summary> /// 数据组合构建 /// </summary> void DataBuild(SlnClass slnClass); }
public class DMImpl : IBaseContainer { private string _name = "DM"; public string Name => _name; public void DataBuild(SlnClass slnClass) { throw new NotImplementedException(); } public void Save() { throw new NotImplementedException(); } }