[英]Passing Type to Method (w/o Generic) (C# Syntax)
I've been looking for a way to create a temporary variable in the construction of a database manager. 我一直在寻找一种在数据库管理器的构造中创建临时变量的方法。
public void Read(string name, string info, Type type){
// blah temp = "Create temporary variable of type above"
database.retrieve(name, info, out temp);
Debug.Log (temp.ToString());
}
I tried passing Generics, but JSON doesn't like methods with Generics. 我尝试传递泛型,但是JSON不喜欢泛型的方法。 I feel like I'm on the verge of figuring it out with
typeof
, but I can't seem to find the syntax. 我觉得我快要用
typeof
弄清楚了,但是我似乎找不到语法。
Edit: The temporary variable contains an overriden ToString()
, so I can't simply out
to and Object
. 编辑:临时变量包含被覆盖的
ToString()
,所以我不能简单地out
并Object
。
If database.retrieve
is a generic method, the best option would be to make the method itself generic: 如果
database.retrieve
是通用方法,最好的选择是使该方法本身通用:
public void Read<T>(string name, string info)
{
T temp;
database.retrieve(name, info, out temp);
// ...
}
Since it's an out
parameter, you don't actually need to instantiate a temporary. 由于这是一个
out
参数,因此实际上不需要实例化一个临时参数。 If it's non-generic, and takes object
, just use object: 如果它是不通用的,需要
object
,只是使用对象:
public void Read(string name, string info, Type type)
{
object temp;
database.retrieve(name, info, out temp);
// ...
}
You can try something like this. 您可以尝试这样。 But this example assumes that your type has parameterless constructor.
但是此示例假定您的类型具有无参数构造函数。 If you use .NET < 4.0 change
dynamic
to Object
. 如果使用.NET <4.0,则将
dynamic
更改为Object
。
public void Read(string name, string info, Type type)
{
ConstructorInfo ctor = type.GetConstructor(System.Type.EmptyTypes);
if (ctor != null)
{
dynamic temp = ctor.Invoke(null);
database.retrieve(name, info, out temp);
Debug.Log(temp.ToString());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.