【问题标题】:In c# ,how to get type in complie time在c#中,如何在编译时获取类型
【发布时间】:2020-08-22 05:24:24
【问题描述】:

在Object-C中,我们可以使用typoef来获取编译时的类型,例如

Myclass *A = new A;
typeof(A) b = A;

在c#中有什么熟悉的东西吗?


编辑 1

我想做什么

//i have a generic function like this, and i can't change it
T getV<T>(string parm)

// i have many members with different type in a class ClassUser
ClassA a;
ClassB b;
Action<int, string, LonglonglonglongClass> c;
...

// when i initialize a ClassUser,i had to write like this 
a = getV<ClassA>("a");
b = getV<ClassB>("b");
c = getV<Action<int, string, LonglonglonglongClass>>("c");
...

//  as you can see , it's annoying, i'd like to write like this
a = getV<typeof(a)>("a");
b = getV<typeof(b)>("b");
c = getV<typeof(c)>("c");
...

编辑 2

找到解决方法

// wrap the getV
void getV2<T>(string parm ,out T ret)
{
   ret = getV<T>(parm);
}

// write like this
getV2("a" ,out a);

【问题讨论】:

  • 您可以随时使用var B = A;
  • 如果您解释您希望该代码做什么,将会有所帮助。没有多少人是 Object-C 和 C# 方面的专家...typeof 确实是对标题中提出的问题的回答(因此是重复的),但是您很有可能正在寻找其他东西。您尝试编译的一些 C# 代码示例也会有所帮助 - 在 C# 中很少知道编译时对象的类型(除非您进行反射),因此可能有更多 C#-ish 解决方案来解决您的实际问题。请edit问题澄清,以便可能重新打开。
  • @AlexeiLevenkov,谢谢,我找到了解决方法
  • 您作为问题一部分的答案是stackoverflow.com/questions/8511066/… 中所述的标准解决方案(将返回类型作为参数类型之一)。如果您实际上还有问题,请务必澄清......(以及您似乎已经在寻找的代码到底是什么)
  • 我认为你需要澄清这个问题是关于什么的。在我看来,您正在尝试编写一个工厂方法,该方法可以创建您拥有现有实例的类型的新实例。

标签: c# typeof


【解决方案1】:
Myclass A = new Myclass();

Type objectType = typeof(Myclass);

Type objectType = A.GetType();

【讨论】:

  • 谢谢,但我想使用模板类型,如Myclass A; A = fun&lt;typeof(A)&gt;("some parm");
  • 如果你想使用泛型类型,你可以像这样将你的类设为泛型类型: public class Myclass 然后获取 T 的类型作为类的属性,比如这:公共类型目的类型{得到{返回类型(T); } }
猜你喜欢
  • 2011-11-20
  • 2013-08-20
  • 1970-01-01
  • 1970-01-01
  • 2014-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多