我正在尝试学习C#泛型,但似乎无法显示数组中的元素。当我调试代码时,如果扩展节点employee,我可以看到元素。但是,当我尝试显示它时,它只是打印出类名而不是实际元素。请看下面。
public class PrintArray<T>
{
public void OutputGeneric(T[] employee)
{
for (int i = 0; i < employee.Length; i++)
{
Console.Write("\n" + employee[i]);//I can't access to FullName and Salary
}
}
}
public class Employee
{
private string Name;
private int Income;
public string FullName
{
set { Name = value;}
get { return Name; }
}
public int Salary
{
set { Income = value; }
get { return Income; }
}
}
class Program
{
static void Main(string[] args)
{
PrintArray<Employee> pa = new PrintArray<Employee>();
Console.Write("\n\Employee: ");
Employee[] customArray = new Employee[3];
customArray[0] = new Employee()
{
FullName = "John Doe",
Salary = 100000
};
customArray[1] = new Employee()
{
FullName = "Mary Jane",
Salary = 50000
};
customArray[2] = new Employee()
{
FullName = "Tyler Smith",
Salary = 80000
};
pa.OutputGeneric(customArray);
Console.ReadLine();
}
}
答案 0 :(得分:5)
在Employee类中重写ToString(并且类似地在您要在PrintArray
中使用的任何其他类中)。
public class Employee
{
private string Name;
private int Income;
public string FullName
{
set { Name = value;}
get { return Name; }
}
public int Salary
{
set { Income = value; }
get { return Income; }
}
public override string ToString()
{
return string.Format("Name: {0}, Salary: {1}", Name, Salary);
}
}
答案 1 :(得分:1)
为了在仍具有通用PrintArray
类和方法的同时实现您最初要寻找的内容,可以通过定义一个委托参数来接近它,该委托参数可用于指定要打印的属性:
public void OutputGeneric(T[] employee, Func<T, dynamic> selector)
{
for (int i = 0; i < employee.Length; i++)
{
Console.Write("\n" + selector(employee[i]));//I still can't access to FullName and Salary
}
}
然后调用此方法如下:
pa.OutputGeneric(customArray, x => new { x.FullName, x.Salary });
提供的输出为:
或者您可以使用以下格式设置输出格式:
pa.OutputGeneric(customArray, x => $"{x.FullName} makes ${x.Salary}");
哪个输出创建为:
答案 2 :(得分:-1)
v=ave(x[,1]==x[,1], x[,1], FUN=cumsum)
t=ave(z[,1]==z[,1], z[,1], FUN=cumsum)
df2 <- x[!paste(x[,1],v) %in% paste(z[,1],t)]
matrix(df2,1,2)
[,1] [,2]
[1,] 4 9
不应是类。您必须覆盖PrintArray
类的ToString
。
Employee