在引用的类库上使用反射

时间:2018-07-11 01:29:53

标签: c# reflection

我有一个班级图书馆

    namespace LabelFieldsCalc
 {
public class LabelFields
{
    // public string "--";
    public string BARCODE128(LabelCarton carton)
    {
        return "01" + carton.EanTun
            + "3102" + carton.WeightBarcode.ToString()
            + "13" + carton.ItemProdnDate.ToString()
            + "21" + carton.EstNO.ToString() + carton.StationNum.ToString() + carton.ItemSerial.ToString() + "9";
    }
    public string BARCODE128HR(LabelCarton carton)
    {
        return "(01)" + carton.EanTun
            + "(3102)" + carton.WeightBarcode.ToString()
            + "(13)" + carton.ItemProdnDate.ToString()
            + "(21)" + carton.EstNO.ToString() + carton.StationNum.ToString() + carton.ItemSerial.ToString() + "9";
    }
    public string BARCODE13PRICE(LabelCarton carton)
    {
        var LvTempEan = carton.ProdExtraKey4.Substring(1, 8);
        var LcPrice = (carton.Price1 * 100).ToString(">>>>");
        int moddigit = ModuloDigit(LvTempEan + LcPrice);
        return LvTempEan + LcPrice;
    }

    private int ModuloDigit(string v)
    {
        //int k = v.Length;
        int tot1 = 0;
        int tot2 = 0;
        for (int i = v.Length; i < 0; i -= 2)
        {
            tot1 += Convert.ToInt16(v.Substring(i, 1));
        }
        tot1 *= 3;
        for (int i = v.Length - 1; i < 0; i -= 2)
        {
            tot2 += Convert.ToInt16(v.Substring(i, 1));
        }

        tot1 += tot2;

        int k = (tot1.ToString().Length);
        int m = Convert.ToInt16(tot1.ToString().Substring(k, 1));
        if (m == 0)
        {
            return 0;
        }
        return 10 - m;
    }
}
}
在项目中引用的

如果可以的话,我可以掌握方法

        LabelFields lv = new LabelFields();
        string value = lv.BARCODE128HR(LL);

但是我真正需要做的是使用反射,以便我可以决定在运行时使用哪种方法计算值

我尝试过的是

        Type type = typeof(LabelFields);
        object obj = Activator.CreateInstance(type);
        string res2 = (string)type.InvokeMember("BARCODE128HR", BindingFlags.InvokeMethod, null, obj, mParam);

这给了我

System.MissingMethodException
  HResult=0x80131512
  Message=Attempted to access a missing member.

要使反射有效,我缺少什么

1 个答案:

答案 0 :(得分:0)

为什么首先需要反思?实例化LabelFields的obj类型后,可以直接调用其方法。

getElementById

编辑: 您的方法名称是一个来自外部的参数。我建议使用枚举和开关:

   Type type = typeof(LabelFields);
   LabelFields obj = (LabelFields)Activator.CreateInstance(type);
   obj.BARCODE128HR(....);
相关问题