[英]Get used or passed datatype of function in c#
Is it possible to grab the type that is used when i call a function ? 我可以调用函数时使用的类型吗?
Sample 样品
public T GetRegData<T>(string v)
{
RegistryKey key = registryPointer();
object oValue = key.GetValue(v, null);
if (oValue != null)
{
string sValue = oValue.ToString().ToLower();
}
if (oValue is T)
{
return (T)oValue;
}
else
{
try
{
return (T)Convert.ChangeType(oValue, typeof(T));
}
catch (InvalidCastException)
{
return default(T);
}
}
}
if I call my function it looks like: 如果我调用函数,它看起来像:
string x = GetRegData<string>("test1");
bool y = GetRegData<bool>("test2");
Now I want to know inside my function what type i try to return. 现在,我想知道函数内部尝试返回的类型。 Not the type of my return data.
不是我的返回数据类型。
Reason: 原因:
key.GetValue(v, null);
Has NULL as parameter. 有NULL作为参数。 But this will deny creating the entry in some cases.
但这在某些情况下会拒绝创建条目。 Eg.
例如。 I try to add a string in the registry, it will simply skip it.
我尝试在注册表中添加一个字符串,它只会跳过它。 It only adds it if I use string!
仅当我使用字符串时才添加它! So the part
所以这部分
key.GetValue(v, XXXXXX );
should be kind of dynamic ^^ 应该是动态的^^
Here some Tesing to code that may show more what I'm trying to do... 这是一些Tesing的代码,可能会显示更多我想做的事情...
public T GetRegData<T>(string v)
{
RegistryKey key = registryPointer();
object oValue;
if ( default(T) is string )
{
oValue = key.GetValue(v, "");
}
else if (default(T) is int)
{
oValue = key.GetValue(v, 0);
}
else if (default(T) is bool)
{
oValue = key.GetValue(v, false);
}
else
{
oValue = key.GetValue(v, null);
}
....
But Defaut( T ) seems to be null anyway.... 但是Defaut(T)似乎还是null。
PS: Please stop voting close when the other question and its answeres doesnt solve my problem. PS:如果其他问题及其答案不能解决我的问题,请停止投票结束。
You can use the typeof
operator. 您可以使用
typeof
运算符。
public T GetRegData<T>(string v)
{
RegistryKey key = registryPointer();
object oValue;
if ( typeof(T) == typeof(string) )
{
oValue = key.GetValue(v, "");
}
else if (typeof(T) == typeof(int))
{
oValue = key.GetValue(v, 0);
}
else if (typeof(T) == typeof(bool))
{
oValue = key.GetValue(v, false);
}
else
{
oValue = key.GetValue(v, null);
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.