问题
I am working on Windows 8 Phone application,I have 2 things here one is Library project and other is normal app,Let me first explain my code:
In Library project
class A
{
public static string empName ="ABC";
public static int empID = 123;
public virtual List<string> ListOfEmployees()
{
List<string> empList = new List<string>
empList.Add("Adam");
empList.Add("Eve");
return empList;
}
}
I have referenced the library project in my child project, My child and Library project are in 2 different solution.
In Child application
class Properties : A
{
public void setValues(){
empName ="ASDF"
ListOfEmployees();
}
public override List<string> ListOfEmployees()
{
List<string> empList = new List<string>
empList.Add("Kyla");
empList.Add("Sophia");
return empList;
}
}
Now in every Child Application we App.xaml.cs
which is the entry point of each project.
In this App.xaml.cs
file i am creating an object of this Properties and calling setValues method.
What i see here is only static variables values are overridden but the methods are not overridden.Why so ? am i doing anything wrong here ?
I get the ASDF and list with Adam and Eve as output
But i need ASDF and list with Kyla and Sophia as output.
How to achieve this ?
EDIT
How i am using these values:
In my Base :
class XYZ : A
{
// now i can get empName as weel as the ListOfEmployees()
string employeeName = null;
public void bind()
{
employeeName = empName ;
ListOfEmployees(); // here is the bug where i always get Adam and Eve and not the Kyla and sophia
}
}
回答1:
Now I understand, you want to call overriden values from your project in your library.
You cannot do that with classical C# mechanisms, for that you need dependency injection. Something along these lines:
// library
public interface IA
{
List<string> ListOfEmployees();
}
public class ABase : IA
{
public virtual List<string> ListOfEmployees() {}
}
public static class Repository
{
private static IA _a;
public static IA A
{
get { return _a = _a ?? new ABase(); }
set { _a = value; }
}
}
// in your app
class Properties : ABase
{
public override List<string> ListOfEmployees() { /* ... */ }
}
Repository.A = new Properties();
回答2:
Change the override keyword to new and you'll get the behaviour you're after. Check out this link for more information on when to use which.
来源:https://stackoverflow.com/questions/22060464/overriding-methods-values-in-app-xaml-cs