5

我需要方法中的类名,例如 X。同时,我不想失去类型安全性,也不会允许其他开发人员将字符串(类名)传递给方法。

像这样的东西:

void X( ??? class) // --> don't know how
{
 var className = get the name of class // --> which I don't know how
 Console.WriteLine(className);
}

X(tblEmployee); //--> usage of X, where tblEmployee is a POCO class
4

3 回答 3

15

您正在寻找的是一个名为 a Type,其中包含有关类的元数据。

您可以在任何实例上使用typeof(class)or方法。.GetType()object

不同的是typeof静态GetType解析并在运行时解析。

void X(Type type)
{
    Console.WriteLine(type.FullName);
}

X(typeof(tblEmployee));
于 2012-12-28T13:13:47.957 回答
7

您可以使用泛型和 的FullName属性Type,例如:

void WriteClassName<TClass>(TClass item)
  where TClass : class {
    Console.WriteLine(item.GetType().FullName);
}

然后TClass根据您的要求应用约束。

于 2012-12-28T13:16:50.550 回答
1
void X(Type type)
{
    if(type == typeof(DesiredType))
    {
          Do Some Action
    }
}
于 2012-12-28T13:23:35.547 回答