Type tableType = Assembly.GetExecutingAssembly().GetType("NameSpace.TableName");
ITable itable = dbcontext.GetTable(tableType);
//prints contents of the table
foreach (object y in itable) {
string value = (string)y.GetType().GetProperty("ColumnName").GetValue(y, null);
Console.WriteLine(value);
}
//inserting into a table
dynamic tableClass = Activator.CreateInstance(tableType);
//Alternative to using tableType, using Tony's tips
dynamic tableClass = Activator.CreateInstance(null, "NameSpace.TableName").Unwrap();
tableClass.Word = userParameter;
itable.InsertOnSubmit(tableClass);
dbcontext.SubmitChanges();
//sql equivalent
dbcontext.ExecuteCommand("INSERT INTO [TableNme]([ColumnName]) VALUES ({0})", userParameter);
public interface IExample
{
void DoSomethingAmazing();
}
public class ExampleA : IExample
{
public void DoSomethingAmazing()
{
Console.WriteLine("AAAA");
}
public void DoA()
{
Console.WriteLine("A")
}
}
public class ExampleB : IExample
{
public void DoSomethingAmazing()
{
Console.WriteLine("BBBB");
}
public void DoB()
{
Console.WriteLine("B")
}
}
然后提供从设置文件序列化的类型
即使在编译之后,我们仍然可以通过使用不同的设置来改变应用程序的行为
例如。
public static class Programm
{
public static void Main()
{
var type = MagicMethodThatReadsASerializedTypeFromTheSettings();
var example = (IExample) Activator.CreateInstance(type);
example.DoSomethingAmazing();
switch(example)
{
case ExampleA a:
a.DoA();
break;
case ExampleB b:
b.DoB();
break;
}
}
}
public ISendable
{
public byte[] ToBytes();
public void FromBytes(byte[] bytes);
}
// Converts any ISendable into a byte[] with the content
// typeBytes + contentBytes
public byte[] ToBytes(ISendable toSend)
{
var typeBytes = Encoding.ASCII.GetBytes(toSend.GetType().AssemblyQualifiedName);
var contentBytes = ISendable.ToBytes();
return MagicMethodToCombineByteArrays(typeBytes, contentBytes);
}
// Coonverts back from byte[] to the according ISendable
// by first reading the type, creating the instance and filling it with
// contentBytes
public T FromBytes<T>(byte[] bytes) where T : ISendable
{
MagicMethodToSplitInputBytes(out var typeBytes, out var contentBytes);
var type = Encoding.ASCII.GetString(typeBytes);
var instance = (T) Activator.CreateInstance(type);
instance.FromBytes(contentBytes);
return instance;
}