【问题标题】:Property under private interface always returns zero私有接口下的属性总是返回零
【发布时间】:2019-09-25 03:59:42
【问题描述】:

我有一个属性的私有接口,所以只有它的所有者类可以创建或读取它,但是当我分配给它时,它就保持为零。

var key = new Key();
((IKey)key).Value = 9;
Debug.Log(((IKey)key).Value);

输出:0

private interface IKey
{
    int Value { get; set; }
}

public struct Key : IKey
{
    int IKey.Value { get; set; }
}

编辑:我也很好奇为什么施法时分配不起作用。

【问题讨论】:

    标签: unity3d interface properties private


    【解决方案1】:

    在设置值之前,您不应将 key 转换为 IKey。它已经继承了该类型,并且您正在屏蔽Key 中设置的Value 属性。顺便说一句,这是一个我更喜欢使用强类型而不是使用var 的弱类型的例子。见下文:

    控制台程序

    namespace Console
    {
        interface IKey
        {
            int Value { get; set; }
        }
    
        public struct Key : IKey
        {
            public int Value { get; set; }
        }
    
        class Program
        {
            static void Main()
            {
                var key = new Key();
                ((IKey)key).Value = 9;
    
                var secondKey = new Key();
                secondKey.Value = 9;
    
                var thirdKey = new Key();
                thirdKey.Value = 9;
    
                System.Console.WriteLine($"key = {((IKey)key).Value}");
                System.Console.WriteLine($"secondKey = {((IKey)secondKey).Value}");
                System.Console.WriteLine($"thirdKey = {thirdKey.Value}");
    
                System.Console.ReadLine();
            }
        }
    }
    

    输出

    key = 0
    secondKey = 9
    thirdKey = 9
    

    【讨论】:

    • 它不允许我在没有强制转换的情况下访问 Value,说它不存在。
    • 这似乎不可能,因为这个解决方案中的代码是完整的。如果您使用其他命名空间,您可能会遇到问题
    • 它绝对不能编译。最简单的类,具有 Key 接口、Key 结构和一个尝试访问它的方法。 Unity 项目,没有命名空间。
    • 您确实有一个带有 Unity 和 C# 的命名空间。见this Stackoverflow question
    • 不知道你想说什么。
    【解决方案2】:

    这是更简单的解决方案

    class Program
    {
        private interface IKey
        {
            int Value { get; set; }
        }
    
        public struct Key : IKey
        {
            int IKey.Value { get; set; }
        }
    
        static void Main()
        {
            IKey key = new Key();
            key.Value = 7;
            System.Console.WriteLine($"key = {key.Value}");
            System.Console.ReadLine();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多