【问题标题】:Get name (string) of new class/struct [duplicate]获取新类/结构的名称(字符串)[重复]
【发布时间】:2016-08-24 12:16:55
【问题描述】:

我正在寻找一种方法来获取在 C# 6 下实例化的类(或结构)的名称。示例:

public class Test
{
public int myvalue;

public Test(int _myvalue){ myvalue= _myvalue;}
}

void Init()
{
    public Test test= new Test(1);
}

void main()
{
    string nameNewTest = // here what I need, that must return "test", not "Test"
}

我看到很多关于查找类型的主题,例如:GetType().Name/nameOf/typeof(Class).Name 或类似的东西,但没有一个新变量的名称。

【问题讨论】:

  • 因为不是实例名,只是变量名。也许您的意思是 nameof(test) (C#6),但由于您的代码 sn-p 不是有效的 c#,因此很难说出在哪里使用它。
  • 你的意思是nameof(Test) 吗?
  • 这甚至不能编译(忽略main)。请尝试更正您的示例并准确解释您想要实现的目标。
  • 请清理您的问题,发布minimal reproducible example 并准确说明您想要什么以及为什么。
  • 你是指实例名“test”还是类名“Test”? (因为,如果你想获得“test”/“Test”,你知道Test test = new Test() 是一个非常糟糕的例子)

标签: c#


【解决方案1】:

你可以使用

string nameNewTest = nameof(Test);

没有 C# 6

string nameNewTest = typeof(Test).Name;

您可以查看this post 的属性/字段

【讨论】:

  • 是,但没有 C# 6。
  • 我编辑了答案,你可以使用typeof(T).Name
  • 看看我的主题的结尾,我已经尝试过 typeof(T).Name 但这给了我“测试”作为我的例子。在您的链接中,这仅适用于字段,不适用于 class=/struct
  • 我不明白,“测试”是从哪里来的?如果您希望您的班级Test 降低使用typeof(Test).Name.ToLower()。如果你想在void Init() 中定义变量public Test test 的名称,你不能在void main() 中得到它,因为有单独的函数。这两个函数在哪里声明?
  • test 是一个新的 Test 类(第 10 行),这是一个例子,只是为了解释我需要什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-04
  • 2017-06-29
  • 2014-10-26
  • 2021-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多