我創建了一個WCF Web服務。序列化類型構建器列表
我想創建一個基於從數據庫返回的信息類型,與數據建立一個類型列表,併發送回來。
但是,我得到的數據合同名稱的
類型「MyDynamicType 'MyDynamicType:http://schemas.datacontract.org/2004/07/' 預計不會。考慮使用DataContractResolver或將任何不知道的類型靜態添加到已知類型的列表中 - 例如,使用KnownTypeAttribute屬性或將它們添加到傳遞給DataContractSerializer的已知類型的列表中。跟蹤查看器中出現 錯誤。
研究異常。它建議將該類型添加到[KnownTypes(Type)]
。我如何用這種方式創建一個類型?
類型生成器類代碼從 How to dynamically create a class in C#?進行了很小的修改。 (即分離創建類型和實例的創建。)
Web服務端點
[OperationContract]
[WebInvoke(Method = "GET",
UriTemplate = "/DB/{Q}")]
List<object> DB(string Q);
Web服務端點代碼
public List<object> DB(string Q)
{
List<object> rows = DLL.DB.RunQuery(IQueries.LoadQuery(Q));
return rows;
}
運行查詢方法
public static List<object> RunQuery(string query)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = query;
connection.Open();
using (SqlDataAdapter da = new SqlDataAdapter(command))
{
DataTable dt = new DataTable();
da.Fill(dt);
Dictionary<string, Type> columns = new Dictionary<string, Type>();
foreach (DataColumn dc in dt.Columns)
{
columns.Add(dc.ColumnName, dc.DataType);
}
Type customType = MyTypeBuilder.CreateNewObject(columns);
List <object> rows = new List<object>();
foreach (DataRow dr in dt.Rows)
{
List<object> row = new List<object>();
foreach (DataColumn col in dt.Columns)
{
object customInstance = MyTypeBuilder.CreateObjectInstance(customType);
PropertyInfo pi = customType.GetProperty(col.ColumnName);
pi.SetValue(customInstance, dr[col]);
row.Add(customInstance);
}
rows.Add(row);
}
return rows;
}
}
}
}
我喜歡的類型生成器
public class MyTypeBuilder
{
public static object CreateObjectInstance(Type myType)
{
var myObject = Activator.CreateInstance(myType);
return myObject;
}
public static Type CreateNewObject(Dictionary<string,Type> values)
{
var myType = CompileResultType(values);
return myType;
}
public static Type CompileResultType(Dictionary<string, Type> values)
{
TypeBuilder tb = GetTypeBuilder();
ConstructorBuilder constructor = tb.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
// NOTE: assuming your list contains Field objects with fields FieldName(string) and FieldType(Type)
foreach (var field in values)
CreateProperty(tb, field.Key, field.Value);
Type objectType = tb.CreateType();
return objectType;
}
private static TypeBuilder GetTypeBuilder()
{
var typeSignature = "MyDynamicType";
var an = new AssemblyName(typeSignature);
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
TypeBuilder tb = moduleBuilder.DefineType(typeSignature
, TypeAttributes.Public |
TypeAttributes.Class |
TypeAttributes.AutoClass |
TypeAttributes.AnsiClass |
TypeAttributes.BeforeFieldInit |
TypeAttributes.AutoLayout |
TypeAttributes.Serializable
, null);
return tb;
}
private static void CreateProperty(TypeBuilder tb, string propertyName, Type propertyType)
{
FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);
PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
MethodBuilder getPropMthdBldr = tb.DefineMethod("get_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType, Type.EmptyTypes);
ILGenerator getIl = getPropMthdBldr.GetILGenerator();
getIl.Emit(OpCodes.Ldarg_0);
getIl.Emit(OpCodes.Ldfld, fieldBuilder);
getIl.Emit(OpCodes.Ret);
MethodBuilder setPropMthdBldr =
tb.DefineMethod("set_" + propertyName,
MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig,
null, new[] { propertyType });
ILGenerator setIl = setPropMthdBldr.GetILGenerator();
Label modifyProperty = setIl.DefineLabel();
Label exitSet = setIl.DefineLabel();
setIl.MarkLabel(modifyProperty);
setIl.Emit(OpCodes.Ldarg_0);
setIl.Emit(OpCodes.Ldarg_1);
setIl.Emit(OpCodes.Stfld, fieldBuilder);
setIl.Emit(OpCodes.Nop);
setIl.MarkLabel(exitSet);
setIl.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(getPropMthdBldr);
propertyBuilder.SetSetMethod(setPropMthdBldr);
}
}
在此先感謝。
當前你的問題的反覆無常。請在您的問題中添加更多選項,以便某人可以重複測試您的問題並重現問題。 –
我不確定除了放入源代碼之外還可以添加哪些內容。 Web服務是非常基礎的。該查詢只是「SELECT * FROM table」。動態類型位於鏈接頁面上。我將放入導致它的代碼片段。並希望有所幫助 – Seige
請在您的問題中添加'TypeBuilder'類代碼並對其進行小修改。 –