【问题标题】:Overriding methods values in App.xaml.cs覆盖 App.xaml.cs 中的方法值
【发布时间】:2014-03-30 09:46:14
【问题描述】:

我正在开发 Windows 8 Phone 应用程序,我这里有两件事,一个是图书馆项目,另一个是普通应用程序,让我先解释一下我的代码:

在图书馆项目中

    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;
      }

}

我在我的子项目中引用了库项目,我的孩子和库项目在 2 个不同的解决方案中。

在子应用程序中

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;
          }
      }

现在在每个子应用程序中,我们 App.xaml.cs 这是每个项目的入口点。

在这个App.xaml.cs 文件中,我正在创建这个Properties and calling setValues method. 的对象

我在这里看到的只是静态变量值被覆盖,但方法没有被覆盖。为什么会这样?我在这里做错了吗?

我得到了 ASDF 并列出了 Adam 和 Eve 作为输出

但我需要 ASDF 并列出 Kyla 和 Sophia 作为输出。

如何做到这一点?

编辑

我如何使用这些值:

在我的基地:

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
       }
    }

【问题讨论】:

    标签: c# wpf windows-phone-8 windows-phone class-library


    【解决方案1】:

    现在我明白了,你想从你的项目中调用被覆盖的值in你的库。

    你不能用经典的 C# 机制来做到这一点,因为你需要依赖注入。大致如下:

    // 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();
    

    【讨论】:

    • 是的,在我的子应用程序中我可以做到这一点并提供实施,但在我的基础上,我还需要有默认的 impl
    • 嗯,您的复杂需求需要复杂的解决方案。见编辑。
    【解决方案2】:

    将 override 关键字更改为 new,您将获得您所追求的行为。查看this link,了解更多关于何时使用哪个的信息。

    【讨论】:

    • 我在问题中显示的代码是相同的,但请确保您尝试使用库项目和普通应用程序
    • 看看这个输出 // TestCars1 // ---------- // 四个轮子和一个引擎。 // 标准运输。 // ---------- // 四个轮子和一个引擎。 // 标准运输。 // ---------- // 四个轮子和一个引擎。 // 载七个人。 // ---------- 在你给我的链接里,你会知道的
    猜你喜欢
    • 1970-01-01
    • 2022-06-21
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 2011-09-15
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多