简体   繁体   English

具有通用类型的方法,设置值

[英]Method with Generic Type, set value

I have a method which is something like below and i want to set the value of it with input string. 我有一个下面的方法,我想用输入字符串设置它的值。

How would i go about it? 我将如何处理? Any advice will be greatly appreciated 任何建议将不胜感激

private static void QueueCheckNAdd<T>(ref T param, string input)
    {
        param.DoSomethingLikeSetValue(input);
    }

for your reference, the generic type is something like int or double 供您参考,泛型类型类似于int或double

param = (T)(object)Convert.ChangeType(input, typeof(T));

必须进行强制转换才能使编译器确信结果确实是T类型。

You want param to be generic (ie, any type), and you expect to be able to call some method on it, correct? 您希望param是通用的(即任何类型), 并且希望能够对其调用某些方法,对吗? Well, you can see the problem there: if param can be any type, there's no way to guarantee that it will have the method DoSomethingLikeSetValue (or whatever). 好了,您可以在那里看到问题:如果param可以是任何类型,则无法保证它将具有DoSomethingLikeSetValue方法(或其他方法)。 I'm sure you could get fancy with introspection or runtime type coercion, but I think the "clean" way to do what you're looking for is to constrain the type of T to some interface that has the required method ( DoSomethingLikeSetValue ). 我敢肯定,您会喜欢自省或运行时类型强制,但我认为做您正在寻找的“干净”方法是将T的类型限制为具有必需方法( DoSomethingLikeSetValue )的某些接口。 Like this: 像这样:

private static void QueueCheckNAdd<T>(ref T param, string input) where T : IHasSomething {
    param.DoSomethingLikeSetValue(input);
}

public interface IHasSomething {
    void DoSomethingLikeSetValue(string s);
}

Then you can invoke QueueCheckNAdd generically only if the generic type supports the IHasSomething interface. 然后,仅当通用类型支持IHasSomething接口时,才可以通用地调用QueueCheckNAdd So you could use it like this: 因此,您可以像这样使用它:

public class Foo : IHasSomething {
    public void DoSomethingLikeSetValue(string s) {
        Console.WriteLine(s);
    }
}

var f = new Foo();
QueueCheckNAdd<Foo>(f, "hello");

Good practice would be to use interface like described before, 好的做法是使用前面所述的界面,

But if you want some fun, you could aslo use the object as a dynamic object, like below: 但是,如果您想获得一些乐趣,则可以将该对象也用作动态对象,如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class SMTHG
    {
        public void DoSomethingLikeSetValue(string input)
        {
            Console.WriteLine("HEYYYYY!!! DYNAMIC OBJECTS FTW!...\n" + input);
        }
    }
    class Program
    {
        private static void QueueCheckNAdd<T>(ref T param, string input)
        {
            dynamic dynamicObject = (dynamic)param; 
            dynamicObject.DoSomethingLikeSetValue(input);
        }
        static void Main(string[] args)
        {
            SMTHG smthg = new SMTHG();
            QueueCheckNAdd(ref smthg, "yoyuyoyo");
        }
    }
}

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

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