如何使用列表从 class 传递数据
How to pass data from class using a list
namespace ConsoleApplication3
{
class A
{
public int a = 100;
}
class Program
{
static void Main(string[] args)
{
ArrayList list = new ArrayList();
A a = new A() ;
list.Add(a);
foreach (var i in list)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
}
}
此代码给出输出:
ConsoleApplication3.A
如何在不使用 .a
和 this
的情况下从 class A
中获取值?我想使用 ArrayList
.
继续实现这一目标
如果您不想使用 .a
和 this
那么为此,您可以使用反射:
using System.Reflection;
...
在你的 foreach 循环中:
FieldInfo[] fields = i.GetType().GetFields(); // All fields of the class A will be here.
foreach (var field in fields)
{
// write out them all
Console.WriteLine(field.GetValue(i));
}
注:
我不确定您的最终目标是什么,但我几乎可以肯定有很多更简单的方法可以做到这一点。
您可以在 class A
中覆盖 ToString()
。
public class A
{
public int a = 100;
public override string ToString()
{
return a.ToString();
}
}
我想这可能就是你要问的:
using System;
using System.Collections;
namespace ConsoleApplication3
{
class A
{
public int a = 100;
}
class Program
{
static void Main(string[] args)
{
var list = new ArrayList();
A a = new A();
list.Add((int)typeof(A).GetField("a").GetValue(a));
foreach (var i in list)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
}
}
namespace ConsoleApplication3
{
class A
{
public int a = 100;
}
class Program
{
static void Main(string[] args)
{
ArrayList list = new ArrayList();
A a = new A() ;
list.Add(a);
foreach (var i in list)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
}
}
此代码给出输出:
ConsoleApplication3.A
如何在不使用 .a
和 this
的情况下从 class A
中获取值?我想使用 ArrayList
.
如果您不想使用 .a
和 this
那么为此,您可以使用反射:
using System.Reflection;
...
在你的 foreach 循环中:
FieldInfo[] fields = i.GetType().GetFields(); // All fields of the class A will be here.
foreach (var field in fields)
{
// write out them all
Console.WriteLine(field.GetValue(i));
}
注:
我不确定您的最终目标是什么,但我几乎可以肯定有很多更简单的方法可以做到这一点。
您可以在 class A
中覆盖 ToString()
。
public class A
{
public int a = 100;
public override string ToString()
{
return a.ToString();
}
}
我想这可能就是你要问的:
using System;
using System.Collections;
namespace ConsoleApplication3
{
class A
{
public int a = 100;
}
class Program
{
static void Main(string[] args)
{
var list = new ArrayList();
A a = new A();
list.Add((int)typeof(A).GetField("a").GetValue(a));
foreach (var i in list)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
}
}