我经常听到反射的糟糕程度.虽然我一般都避免反思,很少发现没有它就无法解决问题的情况,我想知道......
对于那些在应用程序中使用过反射的人,你是否测量过性能命中率,是否真的如此糟糕?
首先,为了让事情更清楚,我将从顶部解释我的情景:
我有一个具有以下签名的方法:
public virtual void SendEmail(String from, List<String> recepients, Object model)
Run Code Online (Sandbox Code Playgroud)
我想要做的是生成一个匿名对象,它具有模型对象的属性以及前两个参数.将模型对象展平为PropertyInfo []非常简单.因此,我想到创建一个包含PropertyInfo和前两个参数的字典,然后转换为匿名对象,其中键是属性的名称,值是属性的实际值.
那可能吗?还有其他建议吗?
现在我再次解释我对词典的热切期待!从我上一个问题的回答中,这个问题在我脑海中浮现!
现在实际的一点是我可以将类转换为字典吗?
在Dictionary中,我希望我的类属性为KEY,特殊属性的值为VALUE
假设我的班级是
public class Location
{
public string city { get; set; }
public string state { get; set; }
public string country { get; set;
}
Run Code Online (Sandbox Code Playgroud)
现在假设我的数据是
city = Delhi
state = Delhi
country = India
Run Code Online (Sandbox Code Playgroud)
现在你可以轻松理解我的观点!
我想制作字典!那本字典应该是这样的
Dictionary<string,string> dix = new Dictionary<string,string> ();
dix.add("property_name", "property_value");
Run Code Online (Sandbox Code Playgroud)
我可以获得价值!但是我怎样才能得到属性名称(而不是价值)?
我应该编码什么来创建它动态!这应该适用于我想要的每一堂课?
你可以理解这个问题
我怎样才能从特定类中获取属性列表?
请考虑以下代码
var currentType = Type.GetType("Some.Type, Some");
dynamic myDynamic = new System.Dynamic.ExpandoObject();
myDynamic.A = "A";
var objectInCorrectType = ???
Run Code Online (Sandbox Code Playgroud)
如何将动态转换为currentType?
我正在尝试使用.NET SDK将以下类保留到DynamoDB:
public class MyClass
{
public string Id { get; set; }
public string Name { get; set; }
public object Settings { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
问题在于Settings属性.它可以是任何类型的对象,我事先并不知道可能分配给它的是什么.当我尝试将其持久化到DynamoDB时,我得到以下异常:
System.InvalidOperationException: 'Type System.Object is unsupported, it has no supported members'
Run Code Online (Sandbox Code Playgroud)
文档模型和对象持久性模型方法都会导致相同的异常.
有没有办法在DynamoDB中保留这些对象?其他数据库(如MongoDB和Azure DocumentDB)可以毫无问题地执行此操作,并且可以将它们反序列化为具有鉴别器的正确类型,或者作为动态JSON对象.
我正在尝试使用 .NET 4.0 中的 System.Runtime.Caching.MemoryCache 类。我有一个通用的方法,因此我可以将任何类型传递到内存缓存中,并在调用时将其取回。
该方法返回一个 object 类型的对象,该对象是具有包含缓存对象的字段 Value 的匿名类型。
我的问题是,如何将要返回的对象转换为其相应的类型?
下面是我的代码...
public static class ObjectCache
{
private static MemoryCache _cache = new MemoryCache("GetAllMakes");
public static object GetItem(string key)
{
return AddOrGetExisting(key, () => InitialiseItem(key));
}
private static T AddOrGetExisting<T>(string key, Func<T> valueFactory)
{
var newValue = new Lazy<T>(valueFactory);
var oldValue = _cache.AddOrGetExisting(key, newValue, new CacheItemPolicy()) as Lazy<T>;
try
{
return (oldValue ?? newValue).Value;
}
catch
{
_cache.Remove(key);
throw;
}
}
/// <summary>
/// How can i access Value …Run Code Online (Sandbox Code Playgroud) c# ×6
.net ×4
dictionary ×2
reflection ×2
asp.net ×1
asp.net-core ×1
generics ×1
memorycache ×1
performance ×1