好吧,我同意上面的用例不是我会使用的。但是,我不同意它没有用处。例如,我们使用枚举来分类机器学习模块的字符串值。我们在运行时编写代码以在运行时使用它,对枚举进行分组比对字符串进行分组和分析要快得多。使用大质量的字符串时没有什么好处。它们在进行比较、内存分配、垃圾收集、分组、排序时会出现问题,字节太多。
管理大量数据的数据库将生成一个字符串的哈希值并存储它,然后在同一语句中比较字符串哈希值(不是唯一的,而是一个数字)和字符串,使 TSQL 语言使用更明确的索引哈希字段以缩小搜索范围,然后比较字符串值以确保使用正确的值。在 TSQL 中,人们会这样做:
SELECT *
FROM Production.Product
WHERE CHECKSUM(N'Bearing Ball') = cs_Pname
AND Name = N'Bearing Ball';
GO
但在 .net 中,我们一直认为比较字符串是可行的方法。
我在这里转储我的代码没有什么意义,因为它是专有的,但是那里有很多好的示例,Bob Dain 的一篇文章逐行展示了如何做到这一点,并且位于 here
他的解决方案的 sn-p 如下所示:
using System;
using System.Reflection;
using System.IO;
namespace RemoteUser
{
public class RemoteUserClass
{
public RemoteUserClass()
{
// Load the remote assembly
AssemblyName name = new AssemblyName();
name.CodeBase = "file://" + Directory.GetCurrentDirectory() +
"ThirdPartyDll.dll";
Assembly assembly = AppDomain.CurrentDomain.Load(name);
// Instantiate the class
object remoteObject =
assembly.CreateInstance("ThirdPartyDll.ThirdPartyClass");
Type remoteType =
assembly.GetType("ThirdPartyDll.ThirdPartyClass");
// Load the enum type
PropertyInfo flagsInfo =
remoteType.GetProperty("ThirdPartyBitFields");
Type enumType = assembly.GetType("ThirdPartyDll.BitFields");
// Load the enum values
FieldInfo enumItem1 = enumType.GetField("AnotherSetting");
FieldInfo enumItem2 = enumType.GetField("SomethingElse");
// Calculate the new value
int enumValue1 = (int)enumItem1.GetValue(enumType);
int enumValue2 = (int)enumItem2.GetValue(enumType);
int currentValue = (int)flagsInfo.GetValue(remoteObject, null);
int newValue = currentValue | enumValue1 | enumValue2;
// Store the new value back in Options.FieldFlags
object newEnumValue = Enum.ToObject(enumType, newValue);
flagsInfo.SetValue(remoteObject, newEnumValue, null);
// Call the method
MethodInfo method = remoteType.GetMethod("DoSomeGood");
method.Invoke(remoteObject, null);
}
}
}
一个人可以使用 System.Reflection.Emit 命名空间做很多事情,一个人可以生成一个类来为一个人制作许可证密钥。也可以写代码,写代码和更新代码才是未来。