Activator.CreateInstance 调用构造函数但返回 null
Activator.CreateInstance calling constructor but returning null
我正在尝试创建泛型类型的实例。我已经尝试通过反射获取构造函数,现在是您将在下面看到的方式,并且两次生成的对象都是空的。
Type type = typeof(StatDefinition<>).MakeGenericType(statTypes[selectedType]);
object definitionObject = Activator.CreateInstance(type, newName, newDescription);
StatTopic.WriteLine(definitionObject);
为了帮助理解变量,statTypes[selectedType] 只是一种基本类型(bool、int、float 等)。对于我的测试,它一直是 typeof(float)。 'newName' 和 'newDescription' 都是字符串。
StatDefinition<> 的构造函数是:
public StatDefinition(string name, string description) : base(name, description)
{
StatTopic.WriteLine(typeof(T));
}
我的控制台首先输出 'System.Single'(来自 StatDefinition 的构造函数),然后是 'null'(definitionObject 为空)。
我似乎找不到原因,显然调用构造函数没有问题,但没有返回新对象。
编辑:统计定义 class 扩展了 Unity3D 的 'ScriptableObject' class,这似乎是问题所在。仍然不确定如何解决这个问题
原来扩展 'ScriptableObject' class(来自 Unity3D)是导致问题的原因。
似乎是基于 Unity 必须初始化其对象的方式。
我正在尝试创建泛型类型的实例。我已经尝试通过反射获取构造函数,现在是您将在下面看到的方式,并且两次生成的对象都是空的。
Type type = typeof(StatDefinition<>).MakeGenericType(statTypes[selectedType]);
object definitionObject = Activator.CreateInstance(type, newName, newDescription);
StatTopic.WriteLine(definitionObject);
为了帮助理解变量,statTypes[selectedType] 只是一种基本类型(bool、int、float 等)。对于我的测试,它一直是 typeof(float)。 'newName' 和 'newDescription' 都是字符串。
StatDefinition<> 的构造函数是:
public StatDefinition(string name, string description) : base(name, description)
{
StatTopic.WriteLine(typeof(T));
}
我的控制台首先输出 'System.Single'(来自 StatDefinition 的构造函数),然后是 'null'(definitionObject 为空)。
我似乎找不到原因,显然调用构造函数没有问题,但没有返回新对象。
编辑:统计定义 class 扩展了 Unity3D 的 'ScriptableObject' class,这似乎是问题所在。仍然不确定如何解决这个问题
原来扩展 'ScriptableObject' class(来自 Unity3D)是导致问题的原因。
似乎是基于 Unity 必须初始化其对象的方式。