c# - C# 中的泛型

标签 c# generics

class Program
{
    static void Main(string[] args)
    {
        HomeFurniture homeFur = new HomeFurniture();
        Check<HomeFurniture,Furniture>(homeFur);
        OfficeFurniture officeFur = new OfficeFurniture();
        Check<OfficeFurniture,Furniture>(officeFur);
    }

    public static void Check<U,T>(T check) where T:Furniture
                                           where U:T
    {
        // I would like to set the properties of HomeFurniture as 
        // MyProperty = 9;
        // and that of OfficeFurniture  as 
        // MyProperty = 10;
    }


    public class HomeFurniture : Furniture
    {
        public int MyProperty { get; set; }
    }

    public class OfficeFurniture: Furniture
    {
        public int MyProperty { get; set; }
    }

    public class Furniture
    {


    }
}

最佳答案

为什么不在Furniture 类中声明MyProperty 然后覆盖它?

例子:

public class Furniture
{
    public virtual int MyProperty {get;}
}

public class HomeFurniture : Furniture
{
    public override int MyProperty
    {
        get
        {
            return 9;
        }
    }
}

public class OfficeFurniture : Furniture
{
    public override int MyProperty
    {
        get
        {
            return 10;
        }
    }
}

关于c# - C# 中的泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/660967/

相关文章:

在 C 中检查对 _Generic() 选择的支持

c# - 在 C# 中将 byte 转换为 sbyte 而不更改位

c# - 使用位操作添加两个数字

c# - 用于在 Visual Studio C# 中展开选定折叠 block /区域的快捷键

java - Java 中菱形运算符 (<>) 的作用是什么?

Java 8 流:myList.stream().map(Foo::bar).collect(Collectors.toList()) 的简写

c# - 获取文件的所有权 C#

c# - 现在更新到 EF5 NotMapped 注释不起作用

generics - 为什么这个通用成员约束不被理解

generics - 如何在F#中声明通用异常类型