كيفية التمييز بين الأسلوب في الأدوية
-
20-09-2019 - |
سؤال
لدي ذاكرة التخزين المؤقت على أساس
Dictionary<MethodBase, string>
يتم تقديم المفتاح من methodbase.getCurrentMethod. كل شيء يعمل بشكل جيد حتى تم الإعلان عن الأساليب بشكل صريح. لكن في يوم من الأيام يبدو أن:
Method1<T>(string value)
يجعل نفس الإدخال في القاموس عندما يحصل T على أنواع مختلفة تمامًا.
لذا فإن سؤالي هو طريقة أفضل لتخزين ذاكرة التخزين المؤقت للطرق العامة. (بالطبع يمكنني توفير الغلاف الذي يوفر getCache والمساواة التي واجهتها أنواع عامة ، ولكن بهذه الطريقة لا تبدو أنيقة).
تحديثهنا ما أريده بالضبط:
static Dictionary<MethodBase, string> cache = new Dictionary<MethodBase, string>();
static void Method1<T>(T g)
{
MethodBase m1 = MethodBase.GetCurrentMethod();
cache[m1] = "m1:" + typeof(T);
}
public static void Main(string[] args)
{
Method1("qwe");
Method1<Stream>(null);
Console.WriteLine("===Here MUST be exactly 2 entry, but only 1 appears==");
foreach(KeyValuePair<MethodBase, string> kv in cache)
Console.WriteLine("{0}--{1}", kv.Key, kv.Value);
}
المحلول
يستخدم Makegenericmethod, ، إذا استطعت:
using System;
using System.Collections.Generic;
using System.Reflection;
class Program
{
static Dictionary<MethodBase, string> cache = new Dictionary<MethodBase, string>();
static void Main()
{
Method1(default(int));
Method1(default(string));
Console.ReadLine();
}
static void Method1<T>(T g)
{
var m1 = (MethodInfo)MethodBase.GetCurrentMethod();
var genericM1 = m1.MakeGenericMethod(typeof(T)); // <-- This distinguishes the generic types
cache[genericM1] = "m1:" + typeof(T);
}
}
نصائح أخرى
هذا غير ممكن؛ طريقة عامة لها قاعدة طريقة واحدة ؛ لا يحتوي على قاعدة طريقة واحدة لكل مجموعة من الوسائط العامة.
لا تنتمي إلى StackOverflow