由于WCF不支持类型,我将类型作为字符串类型传递。例如:
var str= "int"
现在我想将其转换为Type int ,因为我想将CLR类型作为参数传递。
有没有实现这个目标?
答案 0 :(得分:3)
你的意思是使用Type.GetType()?
string typeName = "System.Int32"; // Sadly this won't work with just "int"
Type actualType = Type.GetType(typeName);
答案 1 :(得分:2)
如果类型在当前正在执行的程序集中或在Mscorlib.dll中,则只需获取其名称空间限定的类型名称即可(参见@Rawling answer):
var str = typeof(int).FullName;
// str == "System.Int32"
否则,您需要Type
:
var str = typeof(int).AssemblyQualifiedName;
// str == "System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
然后您可以使用Type.GetType
:
var intType = Type.GetType(str);
修改强>
如果要使用系统别名,可以创建Dictionary<string, Type>
以将所有别名映射到其类型:
static readonly Dictionary<string, Type> Aliases =
new Dictionary<string, Type>()
{
{ "byte", typeof(byte) },
{ "sbyte", typeof(sbyte) },
{ "short", typeof(short) },
{ "ushort", typeof(ushort) },
{ "int", typeof(int) },
{ "uint", typeof(uint) },
{ "long", typeof(long) },
{ "ulong", typeof(ulong) },
{ "float", typeof(float) },
{ "double", typeof(double) },
{ "decimal", typeof(decimal) },
{ "object", typeof(object) }
};
答案 2 :(得分:0)
试试这个
int myInt = 0;
int.TryParse(str, out myInt);
if(myInt > 0)
{
// do your stuff here
}
如果您的意思是您只想发送该类型,请使用
string str = myInt.GetType().ToString();
它会给你类型