我有两个包含相同数据的类,但由于Type
混淆,我无法在两者之间传递值。
这是两个类,
public class Employee
{
public int Key { get; set; }
public string FirstName { get; set; }
public string SecondName { get; set; }
public string FullName => FirstName + " " + SecondName;
public Employee(int key, string first = null, string second = null)
{
Key = key;
FirstName = first;
SecondName = second;
}
}
public class EmployeeList
{
public int Key { get; set; }
public string FirstName { get; set; }
public string SecondName { get; set; }
public string FullName => FirstName + " " + SecondName;
public EmployeeList(int key, string first = null, string second = null)
{
Key = key;
FirstName = first;
SecondName = second;
}
}
然后我使用属性通过LINQ查询存储数据
public ObservableCollection<Employee> Staff { get; set; } =
new ObservableCollection<Employee>();
public ObservableCollection<EmployeeList> StaffAll { get; set; } =
new ObservableCollection<EmployeeList>();
然后我将值传递给每个的属性,
private Employee _selectedEmployee;
public Employee SelectedEmployee
{
get { return _selectedEmployee; }
set
{
_selectedEmployee = value;
NotifyPropertyChanged();
}
}
private EmployeeList _selectedEmployeeAll;
public EmployeeList SelectedEmployeeAll
{
get { return _selectedEmployeeAll; }
set
{
_selectedEmployeeAll = value;
NotifyPropertyChanged();
}
}
例如,
SelectedEmployee = Staff.First();
SelectedEmployeeAll = StaffAll.First();
我想要做的是将值从一个类传递到另一个类,就像这样,
SelectedEmployee = SelectedEmployeeAll;
但粗略的,由于type
冲突,我无法将数据从一个传递到另一个。如何将数据从一种类型传递到另一种类型?
答案 0 :(得分:3)
您应该从Employee
创建EmployeeList
:
SelectedEmployee = new Employee(SelectedEmployeeAll.Key, SelectedEmployeeAll.FirstName, SelectedEmployeeAll.SecondName);
但是你应该尝试只使用一种类型,因为拥有两种相同的类型并不是一个好的设计。
如果您想在多个应用中使用它,请考虑创建共享Class Library
。
答案 1 :(得分:-1)
我无法理解您使用不同名称的一个类。你可以这样做:
public class EmployeeList:Employee
{
public int Key { get; set; }
public string FirstName { get; set; }
public string SecondName { get; set; }
public string FullName => FirstName + " " + SecondName;
public EmployeeList(int key, string first = null, string second = null)
{
Key = key;
FirstName = first;
SecondName = second;
}
}
但我认为,正确的方法是只使用一个班级。