У меня есть универсальный метод, который принимает T, GetResult<T>()
T представляет множество объектов, которые имеют собственный атрибут [JsonProperty(Required = Required.Always)]
в большинстве своих свойств. В пределах GetResult<T>()
мне нужно изменить свойства T на [JsonProperty(Required = Required.Default)]
, и мне нужен следующий метод, который вызывается из GetResult, чтобы получить модифицированную версию T.
Возможно ли это? Если да, то какие настройки мне понадобятся для моей программы ниже?
namespace StackOverflow1
{
using System;
using Newtonsoft.Json;
class Program
{
static void Main(string[] args)
{
GetResult<Person>();
Console.Read();
}
private static T GetResult<T>() where T : Base
{
// Entering this method, T is passed with Name property set to [Required = Required.Always]
// I'm changing T's Name property to [Required = Required.Default]
var properties = typeof(T).GetProperties();
foreach (var property in properties)
{
var customAttributes = property.GetCustomAttributes(true);
foreach (var attribute in customAttributes)
{
if (attribute.GetType().Name == nameof(JsonPropertyAttribute))
{
Console.WriteLine($"Original: {((JsonPropertyAttribute)attribute).Required}");
// this is the change! But it looks like this does not actually change T which I need to forward into BuildSingleResult<T>
((JsonPropertyAttribute)attribute).Required = Required.Default;
Console.WriteLine($"After modification: {((JsonPropertyAttribute)attribute).Required}");
}
}
}
// I need T to be the **modified version** which would have [Required = Required.Default]
return BuildSingleResult<T>();
}
private static T BuildSingleResult<T>() where T : Base
{
// **** this is just to write out JsonPropertyAttribute ***
var props = typeof(T).GetProperties();
foreach (var p in props)
{
var customAttributes = p.GetCustomAttributes(true);
foreach (var attr in customAttributes)
{
if (attr.GetType().Name == nameof(JsonPropertyAttribute))
{
// This shows that T still has [Required = Required.Always] but I need it to have [Required = Required.Default]
Console.WriteLine($"(expecting Default): {((JsonPropertyAttribute)attr).Required}");
}
}
}
// *** end of debug ***
return new Person { Name = "X" } as T;
}
}
class Base
{
[JsonProperty(Required = Required.Always)]
public string Name { get; set; }
}
// This is just to demonstrate using a generic type!
class Person : Base { }
}