我正在使用VS 2010 RTM并尝试使用MetadataTypeAttribute对简单类型执行一些基本验证.当我将验证属性放在主类上时,一切正常.但是,当我把它放在元数据类上时,它似乎被忽略了.我必须遗漏一些微不足道的东西,但我现在已经坚持了一段时间.
我查看了Enterprise Library验证块作为一种解决方法,但它不支持开箱即用的单个属性验证.有任何想法吗?
class Program
{
static void Main(string[] args)
{
Stuff t = new Stuff();
try
{
Validator.ValidateProperty(t.X, new ValidationContext(t, null, null) { MemberName = "X" });
Console.WriteLine("Failed!");
}
catch (ValidationException)
{
Console.WriteLine("Succeeded!");
}
}
}
[MetadataType(typeof(StuffMetadata))]
public class Stuff
{
//[Required] //works here
public string X { get; set; }
}
public class StuffMetadata
{
[Required] //no effect here
public string X { get; set; }
}
Run Code Online (Sandbox Code Playgroud) 我需要在GetHashCode中为BitArray生成快速哈希码.我有一个字典,其中键是BitArrays,所有BitArrays长度相同.
有没有人知道从可变位数生成良好哈希的快速方法,如在这种情况下?
更新:
我最初采用的方法是直接通过反射访问内部int数组(速度比这种情况下的封装更重要),然后对这些值进行异或.XOR方法似乎运行良好,即在"字典"中搜索时,我的"等于"方法不会过度调用:
public int GetHashCode(BitArray array)
{
int hash = 0;
foreach (int value in array.GetInternalValues())
{
hash ^= value;
}
return hash;
}
Run Code Online (Sandbox Code Playgroud)
但是,Mark Byers建议并在StackOverflow其他地方看到的方法稍好一些(对于我的测试数据,XOR为16570等于呼叫,而对于XOR为16608).请注意,此方法修复了前一个错误,其中超出位数组末尾的位可能会影响散列值.如果位数组的长度减少,则可能发生这种情况.
public int GetHashCode(BitArray array)
{
UInt32 hash = 17;
int bitsRemaining = array.Length;
foreach (int value in array.GetInternalValues())
{
UInt32 cleanValue = (UInt32)value;
if (bitsRemaining < 32)
{
//clear any bits that are beyond the end of the array
int bitsToWipe = 32 - bitsRemaining;
cleanValue <<= bitsToWipe;
cleanValue >>= bitsToWipe;
} …Run Code Online (Sandbox Code Playgroud) .net ×2
c# ×2
.net-4.0 ×1
bitarray ×1
dictionary ×1
gethashcode ×1
metadatatype ×1
validation ×1