考虑以下程序:
using System;
namespace Test
{
public static class Tests
{
public static void Test<T>(T value)
{
Console.WriteLine(typeof(T).Name);
}
public static void TestReflection(object value)
{
typeof(Tests).GetMethod("Test")
.MakeGenericMethod(value.GetType())
.Invoke(null, new [] { value });
}
public static void TestDynamic(object value)
{
Test((dynamic)value);
}
}
class Program
{
public static void Main()
{
Tests.Test(new MyPublicType());
Tests.Test(new MyPrivateType());
Console.WriteLine();
Tests.TestReflection(new MyPublicType());
Tests.TestReflection(new MyPrivateType());
Console.WriteLine();
Tests.TestDynamic(new MyPublicType());
Tests.TestDynamic(new MyPrivateType());
Console.ReadKey();
}
public class MyPublicType {}
private class MyPrivateType : MyPublicType {}
}
}
Run Code Online (Sandbox Code Playgroud)
结果输出:
MyPublicType
MyPrivateType
MyPublicType
MyPrivateType
MyPublicType
MyPublicType
Run Code Online (Sandbox Code Playgroud)
您可以看到泛型可以处理私有类型,反射可以处理私有类型,但动态将我的私有类型转换为公共类型.为什么这样做?这种行为是否记录在某处?
我只是在动态调用泛型方法时试图避免使用反射代码.我希望确切的类型匹配,因为我正在检索类型上的属性并在通用静态类中缓存它们以避免字典/锁定模式.
| 归档时间: |
|
| 查看次数: |
46 次 |
| 最近记录: |