如何从创建/调用构造函数的类中提取构造函数的参数?- C#



我通过在构造函数中传递一些参数来调用一个类(Usercontrol(。我还将类实例保存在列表中以执行一些自定义操作。

// In a Main Class
private List<Point> _pList= new List<Point>(); // Point is a UserControl
private void function(header, tx, rx) 
{
Point pt= new Point(header, tx, rx); // all parameters are string and values are dynamic for each class instance
// some operations
_pList.add(pt);
}

在同一类的某个地方,我想通过检查其参数来访问类的一些特殊实例。但是我不知道如何通过它的实例提取类的参数。 这是我想要的伪代码

foreach(var pt in _pList)
{
string header= "something";
string tx = "tx1";
string rx = "rx1";
if(pt.parameter[1]=header && .... ) // just a Pseudo-Code
{
// some tasks
}

}

请指导我如何实现这一目标..谢谢

我假设你的观点看起来 -

public class Point
{
public string Header{get;set;}
public string Tx {get;set;}
public string Rx  {get;set;}
Public Point(string header,string tx,string rx)
{
Header=header;
Tx=tx;
Rx=rx;
}
}

您的代码与创建对象并将其添加到列表的代码相同。

从您的伪代码中,将其更新为 -

foreach(var pt in _pList)
{
string header= "something";
string tx = "tx1";
string rx = "rx1";
if(pt.Header==header && pt.Tx==tx && pt.Rx==rx) // just a Pseudo-Code
{
// some tasks
}

以上是您可以对代码进行的简单更改。

虽然它表明你正在做一些可疑的事情......作为最后的手段,您可以将它们存储在可以访问它们的地方。

例如:

public class PointContainer
{
public Point point {get;set;}
public string header {get;set;}
public string tx{get;set;}
//etc
}

并在您的列表中使用它:

//first create the container:
var pc = new PointContainer() { /* initialize variables */ };
//and put it in your list
_pList.Add(pc);
//your will contain the combination of points and parameters


通常,您将能够访问通过对象本身传递的变量:
var point = new Point(header);
var header = point.Header; //so in your case this public property seems missing

最新更新