我们可以在结构中实现多态性吗?

Can we implement Polymorphism in struct?

我确定这是一个低级问题,但我找不到这个问题的答案。

我认为结构不支持多态,但我的前辈(在采访中)说这是可能的。

有人可以告诉我吗?

我认为你的意思是运行时多态性(方法重载)。我不认为你可以用 Structs 做到这一点,因为结构不支持继承。

您可能需要参考 this article or this article

我认为我们可以进行编译时多态性但不能Runtime.I尝试了下面的代码,令我惊讶的是它成功了!

我尝试了代码,编译时多态性是允许的。代码在下面,但是为什么运行时多态性是不允许的我没有得到,但现在,我想我找到了解决方案。

如有任何意见或指导,我们将不胜感激。

using System;
struct SimpleStruct
{
    private int xval;
    public int X
    {
        get
        {
            return xval;
        }
        set
        {
            if (value < 100)
                xval = value;
        }
    }
    public void DisplayX()
    {
        Console.WriteLine("The stored value is: {0}", xval);
    }
    public void DisplayX(int a)
    {

        Console.WriteLine("The stored value is: {0}", a);
    }
}

class TestClass
{
    public static void Main()
    {
        SimpleStruct ss = new SimpleStruct();
        ss.X = 5;
        ss.DisplayX();
        ss.DisplayX(3);
        Console.ReadLine();
    }
}

嗯,我正在考虑结构可以实现接口的事实...

例如:

public interface IPoint
{
   int X {get;set;}
   int Y {get;set;}
}
public struct Point : IPoint 
{
   public int X { get; set; }
   public int Y { get; set;}
}

public struct AnotherPoint : IPoint
{
     public int X { get; set; }
     public int Y { get; set; }
}

public static void Main () {
    var arr = new IPoint [2];
    arr [0] = new Point () { X = 2 };
    arr [1] = new AnotherPoint () { X = 7 };

    foreach (var p in arr) {
        Console.WriteLine (p.X);
    }
    Console.ReadKey ();
}

结构支持编译时多态性(函数重载和运算符重载),但 运行 时间多态性不支持。结构不支持继承,并且 运行时间多态性是使用基和派生的虚函数概念实现的 class。

因为结构不支持继承,所以不能支持运行时间多态。