发布时间:2025-12-09 11:55:11 浏览次数:1
避免复杂的com引用
using System;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
public class DxComObject : IDisposable
{
private Type _ObjType;
public object ComInstance;
public Type ComType
{
get
{
return _ObjType;
}
}
public object this[string propName]
{
get
{
return _ObjType.InvokeMember(propName, BindingFlags.GetProperty, null, ComInstance, null);
}
set
{
_ObjType.InvokeMember(propName, BindingFlags.SetProperty, null, ComInstance, new object[1]
{
value
});
}
}
public object this[string filedName, BindingFlags flags]
{
get
{
bool flag = 0 == 0;
return _ObjType.InvokeMember(filedName, flags, null, ComInstance, null);
}
set
{
bool flag = 0 == 0;
_ObjType.InvokeMember(filedName, flags, null, ComInstance, new object[1]
{
value
});
}
}
public DxComObject(string ComName)
{
_ObjType = Type.GetTypeFromProgID(ComName, false);
if (_ObjType == null)
{
throw new Exception("指定的COM对象名称无效");
}
ComInstance = Activator.CreateInstance(_ObjType);
}
public object DoMethod(string MethodName, object[] args)
{
return ComType.InvokeMember(MethodName, BindingFlags.InvokeMethod, null, ComInstance, args);
}
public object DoMethod(string MethodName, object[] args, object[] paramMods)
{
ParameterModifier parameterModifier = new ParameterModifier(paramMods.Length);
for (int i = 0; i < paramMods.Length; i++)
{
parameterModifier[i] = Convert.ToBoolean(paramMods[i]);
}
ParameterModifier[] modifiers = new ParameterModifier[1]
{
parameterModifier
};
return ComType.InvokeMember(MethodName, BindingFlags.InvokeMethod, null, ComInstance, args, modifiers, CultureInfo.CurrentCulture, null);
}
public void Dispose()
{
Marshal.ReleaseComObject(ComInstance);
}
}
> 调用1- 登录
DxComObject dxComObject = new DxComObject("U8Login.clsLogin"); array = new object[1] { LoginString }; if (!(bool)dxComObject.DoMethod("ConstructLogin", array)) { throw new Exception("U8登录信息错误!"); } array = new object[8] { "ST", errMsg, errMsg, errMsg, errMsg, errMsg, errMsg, errMsg }; if (!(bool)dxComObject.DoMethod("Login", array)) { throw new Exception(string.Format("登录{0}错误!{1}", "ST", dxComObject["ShareString"].ToString())); } string text = dxComObject["UfDbName"].ToString(); string DBUser = string.Empty; string DBPassword = string.Empty; string text2 = SplitDBInfo(text, out DBUser, out DBPassword);
> 调用2 CO
DxComObject dxComObject2 = new DxComObject("USERPCO.VoucherCO"); array = new object[2] { dxComObject.ComInstance, errMsg }; if (!(bool)dxComObject2.DoMethod("IniLogin", array)) { throw new Exception("初始化CO接口失败!" + array.GetValue(1).ToString()); }