Получить свойство DataContract Name - PullRequest
0 голосов
/ 11 мая 2018

У меня есть класс, к которому я применил атрибут DataContract со свойством name.

[DataContract(Name ="ProductInformation")]
public class ProductViewModel : BaseViewModel
{
   [DataMember]
   public string ProductName {get; set;}
}

Все остальные мои классы ViewModel также наследуются от класса BaseViewModel. Как получить свойство Name изBaseViewModel.

Ответы [ 2 ]

0 голосов
/ 11 мая 2018

PCL BaseViewModel Code

public class BaseViewModel
    {
        public static Dictionary<Assembly, Type> AllAssembelyUsedInBaseViewModel = new Dictionary<Assembly, Type>();
        public static void RegisterAssemblyAndBase(Assembly assembly, Type baseType)
        {
            AllAssembelyUsedInBaseViewModel.Add(assembly, baseType);
        }
        static BaseViewModel()
        {
            RegisterAssemblyAndBase(typeof(BaseViewModel).GetTypeInfo().Assembly, typeof(BaseViewModel));
        }

        public static void GetDataContractNameFromAllAssembly()
        {
            List<string> dname = new List<string>();
            foreach (var item in BaseViewModel.AllAssembelyUsedInBaseViewModel)
            {
                var assembly = item.Key;
                var types = assembly.DefinedTypes.Where(x => x.BaseType == item.Value);

                foreach (var type in types)
                {
                    var attributes = type.GetCustomAttributes(typeof(DataContractAttribute), false);
                    var dt = attributes.FirstOrDefault() as DataContractAttribute;
                if (dt != null)
                {
                    dname.Add(dt.Name);
                }
                }
            }
        }
    }

Регистрация других сборок пользовательского интерфейса

 public MainWindow()
        {
            InitializeComponent();

            BaseViewModel.RegisterAssemblyAndBase(typeof(MainWindow).Assembly, typeof(BaseViewModel));    

        }

Получить все имя Datacontract путем вызова

BaseViewModel.GetDataContractNameFromAllAssembly();
0 голосов
/ 11 мая 2018

Обновление

Если я вас правильно понимаю, вы хотите, чтобы наиболее производный атрибут вызывался из базового класса. Обратите внимание, что typeof (T) получает экземплярный тип, т.е. самый производный тип

Также примечание GetTypeInfo() в основном добавлено, потому что это Xamarin Вопрос

public static List<DataContractAttribute> GetDataContracts<T>()where T : class
{
    return typeof(T).GetTypeInfo()
                    .GetCustomAttributes(false)
                    .OfType<DataContractAttribute>()
                    .ToList();
}

Оригинал

public static List<DataContractAttribute> GetDataContracts<T>()where T : class
{
    return typeof(T).BaseType?
                    .GetCustomAttributes(false)
                    .OfType<DataContractAttribute>()
                    .ToList();
}

public static void Main()
{
    var attribute = GetDataContracts<ProductViewModel>().FirstOrDefault();
    Console.WriteLine(attribute?.Name ?? "NoCigar");
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...