由于 WCF 不支持类型,我将类型作为字符串类型传递。例如:
var str= "int"
现在我想将其转换为 Type int,因为我想将 CLR 类型作为参数传递。
有没有办法做到这一点?
由于 WCF 不支持类型,我将类型作为字符串类型传递。例如:
var str= "int"
现在我想将其转换为 Type int,因为我想将 CLR 类型作为参数传递。
有没有办法做到这一点?
你的意思是喜欢使用Type.GetType()?
string typeName = "System.Int32"; // Sadly this won't work with just "int"
Type actualType = Type.GetType(typeName);
如果该类型在当前执行的程序集中或在 Mscorlib.dll 中,则获得由其命名空间限定的类型名称就足够了(请参阅@Rawling 答案):
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) }
};
试试这个
int myInt = 0;
int.TryParse(str, out myInt);
if(myInt > 0)
{
// do your stuff here
}
如果你的意思是你只想发送类型然后使用
string str = myInt.GetType().ToString();
它会给你类型