使用反射后摆脱对象

时间:2016-01-25 22:10:19

标签: c# object memory reflection

我一直在尝试使用字符串调用方法,但是一个副作用是每次按下按钮时都会创建一个新对象。我怎么能摆脱这个?我尝试过使用null,但没有运气。

首次尝试:

string methodName = cboOriginal.Text + "To" + cboConverted.Text;
Type numeralType = typeof(NumeralSystemConversion);
ConstructorInfo numeralConstructor = numeralType.GetConstructor(Type.EmptyTypes);
object numeralObject = numeralConstructor.Invoke(new object[] { });

MethodInfo numeralMethod = numeralType.GetMethod(methodName);
object numeralValue = numeralMethod.Invoke(numeralObject, new object[] { txtOriginal.Text });

txtConverted.Text = numeralValue.ToString();

numeralType = null; numeralConstructor = null; numeralObject = null;
numeralMethod = null; numeralValue = null;

第二次尝试:

string methodName = cboOriginal.Text + "To" + cboConverted.Text;
convert = typeof(NumeralSystemConversion).GetMethod(methodName).Invoke(typeof(NumeralSystemConversion).GetConstructor(Type.EmptyTypes).Invoke(new object[] { }), new object[] { txtOriginal.Text });
txtConverted.Text = convert.ToString();
convert = null;

应用程序启动时会创建'convert'对象。 NumeralSystemConversion是我创建的类,方法所在的位置。

我所看到的是每次按下按钮时诊断工具(Visual Studio 2015社区)中的内存使用量都会增加。

1 个答案:

答案 0 :(得分:0)

最大的"清理"我看到是创建两个object[] param1 = new object[] { }; object[] param2 = new object[] { null }; 数组(在启动时)并将它们存储在成员变量中:

param2[0] = txtOriginal.Text;
convert = typeof(NumeralSystemConversion).GetMethod(methodName)
    .Invoke(typeof(NumeralSystemConversion).GetConstructor(Type.EmptyTypes)
    .Invoke(param1), param2);
param2[0] = null;

然后在你的方法中:

string

我认为你无法阻止它创建StringBuilder。我担心这是开展业务的成本。 可能帮助的是使用显式StringBuilder methodNameBuilder = new StringBuilder(); 作为另一个类成员:

methodNameBuilder.Clear();
methodNameBuilder.Append(cboOriginal.Text);
methodNameBuilder.Append("To");
methodNameBuilder.Append(cboConverted.Text);
string methodName = methodNameBuilder.ToString();

在你的功能中:

GC.Collect();

最后,内存增加了你可能只是垃圾,在这种情况下String primaryStorage = Environment.getExternalStorageDirectory().getAbsolutePath(); String secondaryStorage = System.getenv("SECONDARY_STORAGE"); Boolean hasSecondary = false; String internalSD = getExternalFilesDir(null) + "/test"; String externalSD = internalSD.replace(primaryStorage, secondaryStorage); try{ File dir = new File(externalSD); dir.mkdirs(); if (dir.isDirectory()) { dir.delete(); hasSecondary = true; } } catch (Exception e) { } 应该清理它们。但在这种情况下,最好不要理会它。