我的问题是基于 this article .
基本上一个类可以实现一个 Freezable 方法来确保一旦对象进入 Frozen 状态就不能更改任何属性。
我有一个遵循这种设计的界面
public interface IFreezableModel
{
void Freeze();
bool IsFrozen{get;}
}
目标是确保在调用 Freeze 方法后,IsFrozen 属性设置为 True,并且对象的属性不能再更改。
为了简化,我将使用一个抽象基类:
public abstract class BaseFreezableModel : IFreezableModel
{
public void Freeze()
{
_isFrozen = true;
}
public bool IsFrozen
{
get {return _isFrozen;}
}
protected ThrowIfFrozen()
{
if (IsFrozen)
throw new Exception("Attempted to change a property of a frozen model");
}
}
这样我就可以上课了
public class MyModel : BaseFreezableModel
{
private string _myProperty;
public string MyProperty
{
get{return _myProperty;}
set
{
ThrowIfFrozen();
_myProperty = value;
}
}
}
这一切都很好也很简单,但是我可以采用哪种策略来确保所有属性都遵循上述模式? (除了编写 setter 和 getter)
这些是我想出的替代方案:
找到一种机制,或许可以使用 emit 将方法注入(inject)到每个属性 setter 中。但我不知道该怎么做,我可能会遇到什么潜在问题(因此需要多长时间)。如果有人知道这一点并能指出我的方向,那就太好了。
在构建过程中使用一些模板,以便在编译时间之前插入对 OnCheckFrozen 的调用。这样做的好处是非常容易理解并且可以用于类似的场景。
找到一个可以为我做所有这些的框架,但这只是一个极端的情况,因为我不允许在这个项目上使用外部框架。
您会使用什么解决方案来实现这一目标?
最佳答案
您正在进入 Aspect Oriented Programming 的世界这里。您可以使用 PostSharp 在 5 分钟内完成此类功能。 - 但似乎不允许您使用外部框架。因此,您的选择归结为实现您自己的非常简单的 AOP 框架,或者只是硬着头皮向每个属性 setter 添加检查。
就我个人而言,我只会在属性 setter 中编写检查。这可能不像您预期的那样痛苦。您可以编写一个 visual studio 代码片段来加快该过程。您还可以编写一个智能单元测试类,该类将使用反射扫描卡住对象的所有属性并尝试设置一个值 - 测试失败如果没有抛出异常..
编辑 响应 VoodooChilds 请求.. 这是一个使用 NUnit 和优秀的 FluentAssertions 库的单元测试类的简单示例。
[TestFixture]
public class PropertiesThrowWhenFrozenTest
{
[TestCase(typeof(Foo))]
[TestCase(typeof(Bar))]
[TestCase(typeof(Baz))]
public void AllPropertiesThrowWhenFrozen(Type type)
{
var target = Activator.CreateInstance(type) as IFreezable;
target.Freeze();
foreach(var property in type.GetProperties())
{
this.AssertPropertyThrowsWhenChanged(target, property);
}
}
private void AssertPropertyThrowsWhenChanged(object target, PropertyInfo property)
{
// In the case of reference types, setting the property to null should be sufficient
// to test the behaviour...
object value = null;
// In the case of value types, just create a default instance...
if (property.PropertyType.IsValueType)
value = Activator.CreateInstance(property.PropertyType);
Action setter = () => property.GetSetMethod().Invoke(target, new object[] { value });
// ShouldThrow is a handy extension method of the FluentAssetions library...
setter.ShouldThrow<InvalidOperationException>();
}
}
此方法使用参数化单元测试来传递被测试的类型,但您同样可以将所有这些代码封装到一个通用基类中(其中 T : IFreezable)并为每个被测试的类型创建扩展类,但是一些测试运行者不喜欢在基类中进行测试。*ahem*Resharper!ahem
EDIT 2 而且,为了好玩,这里有一个 Gherkin 脚本示例,可用于为此类事情创建更灵活的测试 :)
Feature: AllPropertiesThrowWhenFrozen
In order to make sure I haven't made any oversights in my code
As a software developer
I want to be able to assert that all properties of a class throw an exception when the object is frozen
Scenario: Setting the Bar property on the Foo type
Given I have an instance of the class MyNamespace.MyProject.Foo
And it is frozen
When I set the property Bar with a value of 10
Then a System.InvalidOperationException should be thrown
关于c# - 以编程方式在类的每个属性上插入方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7569223/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco
我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer
我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah