简体   繁体   English

如何使用可处理整数或字符串值的泛型创建抽象基类?

[英]How can I create an abstract base class with a generic that can handle either an integer or string value?

I'm learning C# currently and have a situation where I would like to have a base abstract class that other classes will inherit from. 我目前正在学习C#,并且遇到一种情况,我想拥有一个其他类将继承的基本抽象类。

My challenge is that I would like to pass in either an integer or a string value depending on the situation. 我的挑战是我想根据情况传入整数或字符串值。

Currently, I can do that with a generic IF I don't constrain the generic. 目前,我可以使用通用IF来实现此目的,而我不限制通用。 However, I think that might be a bad practice to not constrain a generic? 但是,我认为不限制通用名称可能是一个坏习惯? And if it is a bad practice, how would I constrain the generic so that I'm only taking an integer or string. 而且如果这是一个不好的做法,我将如何约束泛型,以便只使用整数或字符串。

Here's an example of what I'm trying to do: 这是我要执行的操作的一个示例:

/*
I want to have a base abstract class that can handle
both an integer value and a string value
*/
public abstract class Characteristic<T> where T : int, string {
    private T _value;

    public T Value {
        get { return _value;}
        set { _value = value;}
    }
}

public class NumericAttribute : Characteristic<int> {
    private int _modifiedValue = Value + 1;
}

public class StringAttribute : Characteristic<string> {
    private string _modifiedValue = Value + " more text.";
}

Thanks for your help! 谢谢你的帮助!

Limiting a generic class to just int and string is not possible. 将通用类限制为仅intstring是不可能的。

  • there is no "just these classes" constraint 没有“仅这些类”约束
  • int and string do not share any common base class or interface that are unique to them intstring不共享任何唯一的公共基类或接口
  • int is a struct and string is a class - so even narrowing choices by struct / class constraint is not possible. int是一个structstring是一个class -因此,即使通过struct / class约束来缩小选择范围也是不可能的。

So basically generic without type constraints (with possibly checking types at run-time if it is really required) is the best generic type you can get with those 2 types. 因此,基本上没有类型约束的通用类型(如果确实需要,可以在运行时检查类型)是使用这两种类型可以获得的最佳通用类型。 There is nothing particularly wrong with generics that don't constraint they type arguments (ie List<T> ). 没有约束它们键入参数的泛型没有什么特别的错误(即List<T> )。

If you want to narrow types at least a bit int and string do have some shared interfaces - IComparable , IConvertible (non-generic once), but these interfaces are implemented by all numeric types for example. 如果要缩小类型的范围,至少要有一点intstring的确有一些共享的接口IComparableIConvertible (一次非泛型),但是这些接口例如由所有数字类型实现。

Note: there are similar questions trying to limit generics to "numerical types" that may give some alternative approaches (including code generation). 注意:存在类似的问题试图将泛型限制为“数字类型”,这可能会提供一些替代方法(包括代码生成)。 Ie Is there a constraint that restricts my generic method to numeric types? 是否存在将我的通用方法限制为数字类型的约束?

It is possible to more-or-less do what you're asking; 可以或多或少地执行您的要求; but as others have already indicated, you might not want to do that (and might not even need the constraint). 但是正如其他人已经指出的那样,您可能不想这样做(甚至可能不需要约束)。 However, as I indicated in a comment, you make an interface 但是,正如我在评论中指出的那样,您可以创建一个界面

public interface IModifiable<T>
{
    T Modify(T value);
}

and then your own wrapper classes for int and string which implement this interface: 然后是您自己的用于实现此接口的intstring的包装器类:

public struct Int32 : IModifiable<Int32>
{
    public System.Int32 Value { get; set; }

    public Int32 Modify(Int32 value)
    {
        return new Int32() { Value = Value + value.Value };
    }
}

public class String : IModifiable<String>
{
    public System.String Value { get; set; }

    public String Modify(String value)
    {
        return new String() { Value = Value + value.Value };
    }
}

Your base class now has a constraint of your interface 现在,您的基类具有接口的约束

public abstract class Characteristic<T> where T : IModifiable<T>
{
    private T _value;

    public T Value
    {
        get { return _value; }
        set { _value = value; }
    }
}

and your derived classes, pretty much as before 和您的派生类,几乎和以前一样

public class NumericAttribute : Characteristic<Int32>
{
    void f()
    {
        var _modifiedValue = Value.Modify(new Int32() { Value = 1 });
    }
}

public class StringAttribute : Characteristic<String>
{
    void f()
    {
        var _modifiedValue = Value.Modify(new String() { Value = " more text." });
    }
}

Again, while this gives you a "solution" to your specific question, you might consider the wisdom of this approach. 同样,尽管这为您提供了针对特定问题的“解决方案”,但您可能会考虑这种方法的智慧。

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

相关问题 我可以在抽象基类属性中使用泛型集合吗? - Can I use a generic collection in an abstract base class property? 我可以有一个抽象的基类,其key属性是通用的 - can I have an abstract base class with the key attribute being generic 具有抽象方法的基类如何用于处理委托调用? - How can a base class with abstract methods be used to handle delegate calls? 如何使用抽象基类继承内部类? - How can I inherit an inner class using an abstract base class? 如何使用VS2010在T4模板基类中创建抽象Host属性? - How can I create an abstract Host property in a T4 template base class with VS2010? 如何从基本通用抽象类中获取只读字段值 - How to get readonly field value from base generic abstract class 如何声明从另一个抽象类继承的抽象泛型类? - How can I declare an abstract generic class that inherits from another abstract class? 我可以基于抽象基类中定义的某个属性创建派生类的实例吗? - Can I create an instance of a derived class based on a certain property defined in my abstract base class? 我可以创建一个抽象基类UserControl,以便派生.ascx必须实现某些控件吗? - Can I create an abstract base class UserControl so derived .ascx must implement certain controls? 如何使用抽象类创建通用List? - How do I create a generic List using abstract class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM