构造函数的参数 [英] Arguments of constructor
问题描述
我使用以下代码调用构造函数的单个参数
Hi,
I am using following code for calling single arguments of constructor
List<MsgIdTimeStampMap> CANMsgIdList = new List<MsgIdTimeStampMap>();
CANMsgIdList= ReadLogFile(@"\\global.scd.scania.com\home\se\121\valhbc\Desktop\log files\log file with orange\logfile.asc");
var ctors = typeof(MsgIdTimeStampMap).GetConstructors();
var ctor = ctors[0];
ParameterInfo[] pars = ctor.GetParameters();
Console.WriteLine(pars[2]);
Console.ReadKey();
控制台上的结果:
System.String时间戳
这个工作正常。但当我尝试做这样的事情时
Result on console:
System.String timestamp
This is working fine. But when I am trying to do something like this
var ctors = typeof(CANMsgIdList[0]).GetConstructors();
这样会出现一些错误
无法找到类型或命名空间名称'CANMsgIdList'(你是否缺少using指令或程序集引用?
数组大小不能在变量声明中指定(尝试使用'new'表达式初始化)
有谁能帮我解决这个问题???
谢谢
John
It is giving some error like this
The type or namespace name 'CANMsgIdList' could not be found (are you missing a using directive or an assembly reference?
Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
Can anyone help me in solving this???
Thanks
John
推荐答案
尝试:
Try:
var ctors = CANMsgIdList[0].GetType().GetConstructors();
但你没有发布所有代码,因为你得到的错误说在当前命名空间中找不到变量CANMsgIdList。因此,您正尝试在其他地方执行此操作,而未定义CANMsgIdList。请发布您正在使用的不起作用的代码,我可以更好地帮助您。
But you haven't posted all your code, because the error you are getting says that the variable CANMsgIdList can't be found in the current namespace. So you are trying to do that somewhere else that CANMsgIdList isn't defined. Please post the code you are using that doesn't work and I can better help you.
typeof是一个运算符,其中GetType是一种方法。 typeof将整数类型作为参数,其中GetType在运行时从对象提供类型。 2是不同的东西,用法也不同。
详情:
http://stackoverflow.com/questions/983030/type-checking-typeof-gettype-or-is [ ^ ]
在你的情况下,GetType()方法适用于反向构造函数。
示例:
typeof is an operator where GetType is a method. typeof take integral type as an argument where GetType provide type from object at runtime. 2 are different things and usage also different.
for details:
http://stackoverflow.com/questions/983030/type-checking-typeof-gettype-or-is[^]
In your case GetType() method is appropiate for retrive constructors.
Example:
class Program
{
static void Main(string[] args)
{
var emp = new Employee(1, "A");
var list = new List<employee>();
list.Add(emp);
var result = list[0].GetType().GetConstructors();
}
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public Employee(int id, string name)
{
Id = id;
Name = name;
}
}
试试这个..
Try this..
var ctors = CANMsgIdList[0].GetType().GetConstructors();
这是一个编译错误,你应该使用 .GetType()
而不是 typeof(T)
这种情况。
读了这个优秀的答案:
使用gettype-and-typeof获取类型的差异[ ^ ]
It is a compile error, u should use .GetType()
instead of typeof(T)
for this kind of situations.
read this excellent answer:
difference-of-getting-type-by-using-gettype-and-typeof[^]
这篇关于构造函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!