C# 中 怎么获取变量的名字
时间: 2024-02-12 10:04:03 浏览: 46
在 C# 中获取变量的名字有多种方法,以下是其中的两种:
1. 使用 nameof 操作符:nameof 操作符可以返回参数、变量、类型或成员的名称。例如,如果想获取变量 `myVariable` 的名称,可以使用 `nameof(myVariable)`。这将返回字符串 `"myVariable"`。
2. 使用反射:反射是 C# 中一种高级的编程概念,可以在运行时获取程序集中的类型、方法和属性等信息。如果想获取变量 `myVariable` 的名称,可以使用反射来获取该变量所属的字段信息,然后使用 `FieldInfo.Name` 属性来获取其名称。具体代码如下:
```
using System.Reflection;
// 假设 myVariable 是一个 string 类型的变量
string myVariable = "Hello, World!";
// 获取 myVariable 所属的字段信息
FieldInfo fieldInfo = typeof(YourClass).GetField("myVariable", BindingFlags.NonPublic | BindingFlags.Instance);
// 获取字段的名称
string fieldName = fieldInfo.Name;
```
以上是两种获取变量名称的方法,希望对你有所帮助。
相关问题
C# 获取程序的名字
你可以使用以下代码来获取C#程序的名字:
```csharp
string appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
Console.WriteLine(appName);
```
这段代码使用`System.Reflection.Assembly.GetExecutingAssembly().GetName().Name`来获取当前程序的名字,并将其存储在`appName`变量中。然后,通过`Console.WriteLine()`将程序名字打印出来。你可以根据需要将程序名字进行进一步的处理或使用。
C# 获取类中所有变量名字,以及变量类型,并且根据类型调用相应的方法把值传入变量
好的,以下是在 C# 中实现获取类中所有变量名字、类型并根据类型调用相应方法传值的示例代码:
```csharp
using System;
using System.Reflection;
class MyClass
{
public string name;
public int age;
public float height;
public void SetName(string name)
{
this.name = name;
}
public void SetAge(int age)
{
this.age = age;
}
public void SetHeight(float height)
{
this.height = height;
}
public void GetVariables()
{
Type myType = typeof(MyClass);
FieldInfo[] fields = myType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
Type fieldType = field.FieldType;
string fieldName = field.Name;
Console.WriteLine($"Please enter value for {fieldName}: ");
string value = Console.ReadLine();
if (fieldType == typeof(string))
{
MethodInfo method = typeof(MyClass).GetMethod("SetName");
method.Invoke(this, new object[] { value });
}
else if (fieldType == typeof(int))
{
MethodInfo method = typeof(MyClass).GetMethod("SetAge");
method.Invoke(this, new object[] { int.Parse(value) });
}
else if (fieldType == typeof(float))
{
MethodInfo method = typeof(MyClass).GetMethod("SetHeight");
method.Invoke(this, new object[] { float.Parse(value) });
}
}
}
}
public class Program
{
public static void Main()
{
MyClass myClass = new MyClass();
myClass.GetVariables();
Console.WriteLine($"Name: {myClass.name}, Age: {myClass.age}, Height: {myClass.height}");
}
}
```
在这个示例代码中,我们定义了一个`MyClass`类,其中包含了3个公共字段:`name`、`age`和`height`,以及3个设置字段值的方法:`SetName()`、`SetAge()`和`SetHeight()`。`GetVariables()`方法用于获取类中所有字段的名称和类型,并根据类型调用相应的方法传入值。最后,在`Main()`方法中实例化`MyClass`类并调用`GetVariables()`方法来测试这个功能。