开发者

Perform add operation using Generic Concept

开发者 https://www.devze.com 2023-01-09 19:48 出处:网络
I have a class of generic type which accepts 2 parameters . now I need to add these two parameter values and return back the result.

I have a class of generic type which accepts 2 parameters . now I need to add these two parameter values and return back the result.

class AddValue<TText, TValue>

    {
        public AddValue(TText text, TValue value)
        {
            Text = text;
            Value = value;

      开发者_JAVA百科  }
        public TText Text { get; set; }
        public TValue Value { get; set; }
    } 


If you literally mean Add, as in TText + TValue then you have two options here:

  1. You can force them to implement an interface that has an Add method (or whatever), and call that, or

  2. Have the caller pass a delegate that does the addition.

Since unbounded generic type-parameters are effectively object references, you can't operate on them directly. Instead, get the calling code to do the heavy lifting, since they know what to do.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号