简体   繁体   English

具有用户定义类型的通用方法

[英]Generic Methods with user defined types

Scenario I am facing is I have a base class我面临的场景是我有一个基础 class

public class BaseClass
{
    public string SomeVal { get; set; }
    public BaseClass(string someVal)
    {
        this.SomeVal = someVal;
    }
}

and two other classes that inherit from BaseClass using the constructor from BaseClass以及使用 BaseClass 的构造函数从 BaseClass 继承的另外两个类

public class ClassA : BaseClass
{
    public ClassA(string someVal) : base (someVal)
        {
        }
}

and

public class ClassB : BaseClass
{
    public ClassB(string someVal) : base (someVal)
        {
        }
}

I'd like to create a generic method that can take either ClassA types or ClassB types to modify the SomeVal value.我想创建一个可以采用ClassA类型或ClassB类型来修改SomeVal值的通用方法。 I have tried doing this我试过这样做

public static void func<T>(T className)
{
    className.SomeVal = "Hello World";
}

but obviously the compiler doesn't know what SomeVal is, I have also tried public class ClassA<T>: BaseClass but still at the same point of it not knowing what SomeVal is, additionally, all uses of ClassA in the code no longer work with the error Using the generic type 'ClassA<T>' requires 1 type arguments但显然编译器不知道 SomeVal 是什么,我也尝试过public class ClassA<T>: BaseClass但仍然在同一点不知道SomeVal是什么,此外,代码中ClassA的所有使用都不再起作用错误Using the generic type 'ClassA<T>' requires 1 type arguments

I have also considered overloads for the functionality I require, but that can get tedious for my scenario as I have multiple classes that inherit from BaseClass , and the method I would be creating isn't a big one either我还考虑了我需要的功能的重载,但这对于我的场景来说可能会变得乏味,因为我有多个继承自BaseClass的类,而且我要创建的方法也不是一个大的

You can constrain T to BaseClass您可以将T限制为BaseClass

public static void func<T>(T className)
   where T : BaseClass

If you aren't doing much with T , I would consider making func not generic and just take a BaseClass如果您对T做的不多,我会考虑使func不是通用的,而只需使用BaseClass

public static void func(BaseClass className)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM