[英]Treat a string as code in C#
我想要一個方法,注釋或其他讓我將字符串視為C#代碼的東西。
我讀到了CodeDom,Reflection和T4模板,但這不是我想要的。
我希望,我需要的更簡單。 我不希望在運行時生成代碼。
這是一個澄清我想要的例子。 我正在使用VS2010,Entity Framework 5和Code First方法。
我為每個實體類型都有一個Insert方法。 以下是插入Cliente
(Costumer)的方法的代碼。 如果數據庫中存在Cliente
,則更新而不是插入:
public int InsertarCliente(Cliente cliente)
{
int id = cliente.ClienteId;
try
{
if (id != -1)
{
var clt = db.Clientes.Find(id);
clt.Nombre = cliente.Nombre;
clt.Apellido1 = cliente.Apellido1;
clt.Apellido2 = cliente.Apellido2;
// more similar statements
}
else
db.Clientes.Add(cliente);
db.SaveChanges();
return cliente.ClienteId;
}
catch (DbEntityValidationException exc)
{
// code
}
}
我試圖使用CodeDom創建一個適用於任何實體類型的泛型方法。 該方法不起作用,我知道原因:CodeDom不編譯和運行任意代碼,它需要額外的命名空間,使用語句,類,方法等。這種方法不起作用,這里是代碼來澄清我的意思試圖這樣做:
public int Insertar<TEntity>(TEntity entidad, string[] atributos)
where TEntity : class
{
string nombreEntidad = entidad.GetType().Name;
string entidadId = nombreEntidad + "Id";
string tabla = nombreEntidad + "s";
int id = Convert.ToInt32(
entidad.GetType().GetProperty(entidadId).GetValue(entidad, null));
try
{
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters cp = new CompilerParameters();
cp.GenerateExecutable = false;
cp.GenerateInMemory = true;
CompilerResults cr;
string codigo;
if (id != -1)
{
codigo = "var entidadAlmacenada = db." + tabla + ".Find(id);";
cr = codeProvider.CompileAssemblyFromSource(cp, codigo);
CompilerResults cr2;
string codigoActualizador;
foreach (string atr in atributos)
{
codigoActualizador =
"entidadAlmacenada." + atr + " = entidad." + atr + ";";
cr2 = codeProvider.CompileAssemblyFromSource(
cp, codigoActualizador);
}
}
else
{
codigo = "db." + tabla + ".Add(entidad);";
cr = codeProvider.CompileAssemblyFromSource(cp, codigo);
}
db.SaveChanges();
return Convert.ToInt32(
entidad.GetType().GetProperty(entidadId).GetValue(entidad, null));
}
catch (DbEntityValidationException exc)
{
// code
}
}
我想要一種方法將表示代碼的字符串轉換(內聯)到它所代表的代碼。
就像是:
string code = "line of code";
code.toCode(); // or
toCode(code); // or
[ToCode]
code;
對不起,如果我寫得太多了,但這次我想說清楚。
我需要的是一個字符串“包含代碼”在編譯之前被代碼替換。 沒有運行時編譯或執行。
有沒有辦法做那樣的事情?
TIA
編輯:
上面的例子只是一個例子。 但在任何情況下我都想要“字符串轉換代碼”。
看看CSScript
CS-Script是一種基於CLR(公共語言運行時)的腳本系統,它使用符合ECMA的C#作為編程語言。 CS-Script目前主要針對Microsoft實現CLR(.NET 2.0 / 3.0 / 3.5 / 4.0 / 4.5),並在Mono上提供全面支持。
PS。 從您的示例來看,您應該花時間編寫通用數據庫存儲庫,而不是在運行時生成代碼。
我有一種感覺,你正在使用動態代碼生成錯誤的樹。
這周末我做了一些非常相似的事。 它將表從ODBC傳輸到EF。
對不起,我沒時間做這個更緊湊的例子。 雖然它是通用的,但我認為它與你所要求的非常相似:
using Accounting.Domain.Concrete;
using Accounting.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Design.PluralizationServices;
using System.Data.Entity.Migrations;
using System.Data.Odbc;
using System.Globalization;
using System.Linq;
namespace QuickBooks.Services
{
public class QuickBooksSynchService
{
string qodbcConnectionString = @"DSN=QuickBooks Data;SERVER=QODBC;OptimizerDBFolder=%UserProfile%\QODBC Driver for QuickBooks\Optimizer;OptimizerAllowDirtyReads=N;SyncFromOtherTables=Y;IAppReadOnly=Y";
PluralizationService pluralizationService = PluralizationService.CreateService(CultureInfo.CurrentCulture);
readonly int companyID;
public QuickBooksSynchService(string companyName)
{
// Make sure the name of QODBC company is same as passed in
using (var con = new OdbcConnection(qodbcConnectionString))
using (var cmd = new OdbcCommand("select top 1 CompanyName from Company", con))
{
con.Open();
string currentCompany = (string)cmd.ExecuteScalar();
if (companyName != currentCompany)
{
throw new Exception("Wrong company - expecting " + companyName + ", got " + currentCompany);
}
}
// Get the company ID using the name passed in (row with matching name must exist)
using (var repo = new AccountingRepository(new AccountingContext(), true))
{
this.companyID = repo.CompanyFileByName(companyName).CompanyId;
}
}
public IEnumerable<T> Extract<T>() where T : new()
{
using (var con = new OdbcConnection(qodbcConnectionString))
using (var cmd = new OdbcCommand("select * from " + typeof(T).Name, con))
{
con.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var t = new T();
// Set half of the primary key
typeof(Customer).GetProperty("CompanyId").SetValue(t, this.companyID, null);
// Initialize all DateTime fields
foreach (var datePI in from p in typeof(Customer).GetProperties()
where p.PropertyType == typeof(DateTime)
select p)
{
datePI.SetValue(t, new DateTime(1900, 1, 1), null);
}
// Auto-map the fields
foreach (var colName in from c in reader.GetSchemaTable().AsEnumerable()
select c.Field<string>("ColumnName"))
{
object colValue = reader[colName];
if ((colValue != DBNull.Value) && (colValue != null))
{
typeof(Customer).GetProperty(colName).SetValue(t, colValue, null);
}
}
yield return t;
}
}
}
public void Load<T>(IEnumerable<T> ts, bool save) where T : class
{
using (var context = new AccountingContext())
{
var dbSet = context
.GetType()
.GetProperty(this.pluralizationService.Pluralize(typeof(T).Name))
.GetValue(context, null) as DbSet<T>;
if (dbSet == null)
throw new Exception("could not cast to DbSet<T> for T = " + typeof(T).Name);
foreach (var t in ts)
{
dbSet.AddOrUpdate(t);
}
if (save)
{
context.SaveChanges();
}
}
}
}
}
嘗試使用新的.net框架的功能,允許您將Roslyn API用於編譯器。
您可以從使用Roslyn的Read-Eval-Print Loop示例獲得所需的代碼示例:
http://gissolved.blogspot.ro/2011/12/c-repl.html http://blogs.msdn.com/b/visualstudio/archive/2011/10/19/introducing-the-microsoft-roslyn-ctp的.aspx
我個人只是實現了一個通用的存儲庫模式(在google和asp.net mvc網站上有很多結果),它暴露了一個IQueryable集合,所以你可以直接查詢IQueryable集合
另一種(和imho首選)方法來實現你想要做的是使用db.Set<TEntity>().Find(id)
等
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.