如何从带参数的构造函数创建对象
How can I create object from constructors with parameters
这段代码在默认构造函数中运行良好。如何从带参数的构造函数创建对象?
private readonly JsonSerializer _serializer;
private static readonly IReadOnlyDictionary<TypeId, Type> _derivedTypes;
static ByTypeIdConverter()
{
var baseType = typeof(T);
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
_derivedTypes = (
from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
from assemblyType in domainAssembly.GetTypes()
where !assemblyType.IsAbstract && assemblyType.IsSubclassOf(baseType)
select assemblyType).ToDictionary(t => (TypeId)t);
}
public override T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer)
{
var jObject = JObject.Load(reader);
var typeId = jObject["_t"]?.ToObject<TypeId>();
if (typeId is null || !_derivedTypes.TryGetValue(typeId, out var classType))
throw new JsonSerializationException("Failed to get derived class type from json or found type was not expected");
var creator = _serializer.ContractResolver.ResolveContract(classType).DefaultCreator;
if (creator is null)
{
throw new JsonSerializationException($"Failed create instance of type {classType.Name}");
}
var result = creator();
_serializer.Populate(jObject.CreateReader(), result);
return (T)result;
}
一些附加信息我有 SomeBase class 和该基础的自定义 JsonConverter class。我只是像这样反序列化:
JsonConvert.DeserializeObject<SomeBase>(jsonData);
我创建了未初始化的对象。这帮助我解决了我的问题
if (creator is null)
creator = () => RuntimeHelpers.GetUninitializedObject(classType);
这段代码在默认构造函数中运行良好。如何从带参数的构造函数创建对象?
private readonly JsonSerializer _serializer;
private static readonly IReadOnlyDictionary<TypeId, Type> _derivedTypes;
static ByTypeIdConverter()
{
var baseType = typeof(T);
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
_derivedTypes = (
from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
from assemblyType in domainAssembly.GetTypes()
where !assemblyType.IsAbstract && assemblyType.IsSubclassOf(baseType)
select assemblyType).ToDictionary(t => (TypeId)t);
}
public override T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer)
{
var jObject = JObject.Load(reader);
var typeId = jObject["_t"]?.ToObject<TypeId>();
if (typeId is null || !_derivedTypes.TryGetValue(typeId, out var classType))
throw new JsonSerializationException("Failed to get derived class type from json or found type was not expected");
var creator = _serializer.ContractResolver.ResolveContract(classType).DefaultCreator;
if (creator is null)
{
throw new JsonSerializationException($"Failed create instance of type {classType.Name}");
}
var result = creator();
_serializer.Populate(jObject.CreateReader(), result);
return (T)result;
}
一些附加信息我有 SomeBase class 和该基础的自定义 JsonConverter class。我只是像这样反序列化:
JsonConvert.DeserializeObject<SomeBase>(jsonData);
我创建了未初始化的对象。这帮助我解决了我的问题
if (creator is null)
creator = () => RuntimeHelpers.GetUninitializedObject(classType);