c#使用string和int返回的泛型方法

时间:2017-02-28 11:19:32

标签: c# string generics return

我实现了一个读取PLC中变量值的代码。值可以是任何类型(bool,string,int16,int32等)。 实际上我使用强制转换实现了这个代码。 但是现在我看到了强制转换盒子/拆箱,这对于干净的内存使用来说是一个坏主意。 所以我试图使用在运行时链接的通用方法类型来创建相同的行为。 所以这是我的代码与评论。 这适用于所有结构类型(bool,int32),但不适用于类类型(String),你能告诉我到目前为止我错过了什么。

namespace Template_String
{
class Program
{    
    public int num1 = 33;
    public static string PLCstrvar = "PLCvarName";

    static void Main(string[] args)
    {
        Console.WriteLine((Int32)Readwrite.READ(PLCstrvar));//working with cast
        Console.WriteLine(Readwrite.READImp2<Int32>(PLCstrvar));//Working with generics
        Console.WriteLine(Readwrite.READImp2<String>(PLCstrvar));//not working
    }
}
public static class Readwrite
{
    //the actual code 
    public static object READ(String PLCVariableName, Boolean WorkingDATA = false)
    {//my code return an type object which is not really good regarding box / unbox implementation
        //I'd like to do something like
        String returnstr = FINDSYMBOL(PLCVariableName, WorkingDATA);
        if (returnstr != "")
        {
            return _plcClient.ReadSymbol(returnstr);
        }
        return "";
    }
    //the projected code
    public static T READImp2<T>(String PLCVariableName, Boolean WorkingDATA = false) where T : new()
    {//The new code uses generics but that doesn't work with String as they are Class and not struct as Boolean are
        //I'd like to do something like
        dynamic returnstr = new T();//resolved in runtime
        returnstr = FINDSYMBOL(PLCVariableName, WorkingDATA);
        if (returnstr != "")
        {
            return(T)_plcClient.ReadSymbol(PLCVariableName);
        }
        return (T)false;//not good
    }

    public static String FINDSYMBOL(String strvalueToreach, Boolean WorkingDATA = false)
    {
        String StrValueToReach = "";
        if (!WorkingDATA)
        {
            for (int inc = 2; inc < 10; inc++)
            {
                StrValueToReach = strvalueToreach;
                if (_plcClient.SymbolExists(StrValueToReach))
                {
                    return StrValueToReach;
                }
                else
                {
                    return "null";
                }
            }
        }
        return "null";
    }
}

/ 编辑这是一个由远离我的XY开发人员开发的黑匣子。此代码仅用于使代码在没有代码的情况下运行!! /

public static class _plcClient  //PLC dynamic link !!dummy code implemented elsewhere!!
    {
    /* this code return if the symbole exist and its value in Int32, Int16, String, Boolean.... type.*/
        private static string nullable="";
        public static bool SymbolExists(string value) { return true;}
        public static object ReadSymbol(String value) { return nullable = "toto"; }
    }
 }

0 个答案:

没有答案