In lua, one can very easily create a table and add functions to it.
How do I do that in C#? My first idea was to use a List of delegates and fill the list with anonymous functions, but I can't get the syntax right.
public class PlanItem
{
public string Name { get; set; }
public List<BusinessRule> Rules;
}
public delegate bool BusinessRule(PlanItem item);
[Test]
public void TestIt()
{
PlanItem item = new PlanItem();
item.Rules.Add(
BusinessRule(PlanItem item)
{
return !string.IsNullOrEmpty(item.Name);
}
);
foreach(BusinessRule rule in item.Rules)
{
if(!rule(item))
// write uh-oh
}
}
This should do the trick:
item.Rules.Add((planItem) =>
{
return !string.IsNullOrEmpty(planItem.Name);
});
public void TestIt()
{
PlanItem item = new PlanItem();
item.Rules.Add( (item) => { !string.IsNullOrEmpty(item.Name); });
item.Rules.ForEach( (rule) => { if(!rule(item) uhOh(item, outputStream);} );
}
In C# 2.0 without anonymous delegates:
BusinessRule rule = delegate(PlanItem planitem) {
return !string.IsNullOrEmpty(planitem.Name);
};
item.Rules.Add(rule);
Related
I have a list of Func and I want to add elements.
If I add them on Start like below, no problem:
public List<System.Func<bool>> conditions = new List<System.Func<bool>>();
void Start()
{
conditions.Add(Iamdead);
conditions.Add(Iamalive);
}
bool Iamdead()
{
...
return ...;
}
bool Iamalive()
{
...
return ...;
}
But I want to define the list without Start so that I have a clean list of methods that I can see as elements in a row. I have tried the classic format:
public List<System.Func<bool>> conditions = new List<System.Func<bool>>()
{
bool Iamdead()
{
...
return ...;
}
,
bool Iamalive()
{
...
return ...;
}
};
This gave me parsing error
I tried like that:
public List<System.Func<bool>> conditions = new List<System.Func<bool>>()
{
Iamdead,Iamalive
};
static bool Iamdead()
{
...
return ...;
}
static bool Iamalive()
{
...
return ...;
}
This worked only if the methods are static but I do not want them to be static. Without static, it doesn't work. It seems I couldn't understand the data structure here. Can anyone tell me the correct way of defining Func in a list?
Thanks
I strongly suspect the problem is that you're trying to access this (implicitly) within a field initializer. You're not allowed to do that. Just move the initialization into a constructor:
// You don't really use public fields, do you?
private readonly List<Func<bool>> conditions;
public MyClass()
{
conditions = new List<Func<bool>> { Method1, Method2 };
}
private bool Method1() { ... }
private bool Method2() { ... }
(I'm assuming you actually want your conditions to depend on state within the instance. If they don't, you don't need this. If the methods aren't used other than for these conditions, and they're short enough, you might want to use lambda expressions instead.)
Like so:
public List<System.Func<bool>> conditions = new List<System.Func<bool>>()
{
() => false,
() => true,
};
You can just use lambdas:
public List<System.Func<bool>> conditions = new List<System.Func<bool>>()
{
() =>
{
return false;
}
,
() =>
{
return true;
}
};
I have a the following operation:
public void Save (Customer c, IEnumerable <Product> products)
{
// Validate that you have entered at least one product.
if (!produtos.Any())
throw new ArgumentOutOfRangeException("products");
}
Inline, without using inheritance (eg AbstractValidator ), as would this same operation using the FluentValidation library?
This is not supported yet:
public void DoOperation(List<string> strings)
{
var validator = new InlineValidator<List<string>>();
validator.RuleFor(l => l).Must(l => l.Any()).WithMessage("No one");
validator.ValidateAndThrow(strings)
}
On this case, we have to throw ValidationException manually.
like:
public void DoOperation(List<string> strings)
{
if (!strings.Any())
{
var failures = new List<ValidationFailure>();
failures.Add(new ValidationFailure("strings", "Must have at less one."));
throw new ValidationException(failures);
}
}
See:
https://fluentvalidation.codeplex.com/discussions/579227
var validator = new InlineValidator<Person>();
validator.RuleSet("SomeRuleset", ()=>{
validator.RuleFor(x=>x.Name)...etc
});
https://github.com/FluentValidation/FluentValidation/issues/563
I think this kind of validation is impossible, if you had an object which had a property of type IEnumerable<Product> you could using FluentValidation to check if the object has at least one product.
for example
public class ProductList
{
IEnumerable<Product> Products {get;set;}
var Validator = new ProductListValidator();
public bool IsValid
{
get
{
var res = Validator.Validate(this);
return res.IsValid;
}
}
public IList<ValidationFailure> ValidationResult
{
get
{
var res = Validator.Validate(this);
return res.Errors;
}
}
}
public class ProductListValidator : AbstractValidator<ProductList>
{
public ProductListValidator()
{
RuleFor(i => i.Products).Must(i => i.HasAny()).WithMessage("Your Error Meesage");
}
}
then
public void Save (Customer c, ProductList products)
{
// Validate that you have entered at least one product.
if (!ProductList.IsValid)
{
ReturnErrorSummary(ProductList.ValidationResult);
}
}
Today, I searched a line of code which was written like:
SomeObject.SomeFunction().SomeOtherFunction();
I am unable to understand this. I tried to search it on Google about this but no luck.
Please help me to understand this.
SomeObject has a function called SomeFunction(). This function returns an object (of an unknown type for us, based on your example). This object has a function called SomeOtherFunction().
The question "how to implement" is a bit vague to answer, though.
Consider the following
public class FirstClass
{
public SecondClass SomeFunction()
{
return new SecondClass();
}
}
public class SecondClass
{
public void SomeOtherFunction()
{
}
}
So the following are equivalent.
FirstClass SomeObject = new FirstClass();
SomeObject.SomeFuntion().SomeOtherFunction();
OR
FirstClass SomeObject = new FirstClass();
SecondClass two = SomeObject.SomeFuntion();
two.SomeOtherFunction();
This is called Fluent coding or method chaining and is a method of programming that allows you to chain commands together. It is very common in LINQ where you might have something like this:
var result = myList.Where(x => x.ID > 5).GroupBy(x => x.Name).Sort().ToList();
This would give you all the records greater than 5, then grouped by name, sorted and returned as a list. The same code could be written in long hand like this:
var result = myList.Where(x => x.ID > 5);
result = result.GroupBy(x => x.Name);
result = result.Sort();
result = result.ToList();
But you can see this is much more long winded.
This style of programming called FluentInterface style.
Eg:
internal class FluentStyle
{
public FluentStyle ConnectToDb()
{
// some logic
return this;
}
public FluentStyle FetchData()
{
// some logic
return this;
}
public FluentStyle BindData()
{
// some logic
return this;
}
public FluentStyle RefreshData()
{
// some logic
return this;
}
}
And the object can be created and method can be consumed as below;
var fluentStyle = new FluentStyle();
fluentStyle.ConnectToDb().FetchData().BindData().RefreshData();
This type of chaining may involve extension methods. These allow addition of new methods to existing classes (even those that you don't have the source code for).
e.g.
public static class StringExtender
{
public static string MyMethod1(this string Input)
{
return ...
}
public static string MyMethod2(this string Input)
{
return ...
}
}
....
public string AString = "some string";
public string NewString = AString.MyMethod1().MyMethod2();
This can be done using extension methods
public class FirstClass
{
}
public class SecondClass
{
}
public class ThridClass
{
}
public static class Extensions
{
public static SecondClass GetSecondClass(this FirstClass f)
{
return new SecondClass();
}
public static ThridClass GetThridClass(this SecondClass s)
{
return new ThridClass();
}
}
}
AND then you can ues
FirstClass f= new FirstClass();
f.GetSecondClass().GetThridClass();
Suppose I have a base class named Visitor, and it has 2 subclass Subscriber and NonSubscriber.
At first a visitor is start off from a NonSubscriber, i.e.
NonSubscriber mary = new NonSubscriber();
Then later on this "mary" subscribed to some services, and I want to change the type of "mary" to Subscriber.
What is the conventional way to do that?
can't do that. sorry. C# is not a dynamic language.
You will have to create a new mary = new Subscriber(); and copy all relevant properties.
But a better approach might be to model it differently: Give Visitor a list of subscriptions. An empty list means a NonSubscriber.
You cant do this type of conversion.
What you should do is treat mary as a visitor, and when time arrives, create a new instance of "subscriber":
Visitor mary = new NonSubscriber();
// Do some Visitor operations
...
// Now mary is a Subscriber
mary = new Subscriber();
You could use the GOF design patterns State or Strategy to model such an behaviour. Using these patterns, it seems during runtime as if the class of the objects has been changed.
It seems that you have some design problems. I think that it would be better to redesign your code like:
class Visitor
{
private bool isSubscriber = false;
public bool IsSubscriber
{
get { return isSubscriber; }
}
public void Subscribe()
{
// do some subscribing stuff
isSubscriber = true;
}
public void Unsubscribe()
{
// do some unsubscribing stuff
isSubscriber = false;
}
}
You cannot change the type of a variable at runtime. You need to create a new instance.
mary = new Subscriber();
Create a Subscriber constructor that takes a NonSubscriber object as a parameter, or create a method on the NonSubscriber object that returns a Subscriber to save you having to writer the mappping code in multiple places.
It seems like you are encoding information incorrectly into your class hierarchy. It would make more sense to use a different pattern than sub classing here. For example, use only one class (visitor, or perhaps you could name it potential subscriber, whatever seems appropriate) and encode information on the services the object is subscribed to, moving the dynamically changing behavior behind a "Strategy" pattern or some such. There's very little detail in your example, but one thing you could do in C# is to make a "subscriber" property which would change the behavior of the object when the state of the property was changed.
Here's a contrived somewhat related example:
class Price
{
private int priceInCents;
private bool displayCents;
private Func<string> displayFunction;
public Price(int dollars, int cents)
{
priceInCents = dollars*100 + cents;
DisplayCents = true;
}
public bool DisplayCents
{
get { return displayCents; }
set
{
displayCents = value;
if (displayCents)
{
this.displayFunction = () => String.Format("{0}.{1}", priceInCents / 100, priceInCents % 100);
}
else
{
this.displayFunction = () => (priceInCents / 100).ToString();
}
}
}
public string ToString()
{
return this.displayFunction();
}
}
public class User
{
public Subscription Subscription { get; set; }
public void HandleSubscription()
{
Subscription.Method();
}
}
public abstract class SubscriptionType
{
public abstract void Method();
}
public class NoSubscription : SubscriptionType
{
public override void Method()
{
// Do stuff for non subscribers
}
}
public class ServiceSubscription : SubscriptionType
{
public override void Method()
{
// Do stuff for service subscribers
}
}
public class Service2Subscription : SubscriptionType
{
public override void Method()
{
// Do stuff for service2 subscribers
}
}
Think the code explains my answer :)
Adding to the other answers and your comment, you indeed can use the state pattern for your purpose, it would go something like this:
public class MyProgram
{
public void Run()
{
Visitor v = new Visitor("Mary");
Debug.Assert(v.SubscriptionLinkText == "Join now");
v.IsSubscribed = true;
Debug.Assert(v.SubscriptionLinkText == "Today's special");
v.IsSubscribed = false;
Debug.Assert(v.SubscriptionLinkText == "Join now");
}
}
public class Visitor
{
public string Name { get; set; }
private bool _isSubscribed;
public bool IsSubscribed
{
get { return this._isSubscribed; }
set
{
if (value != this._isSubscribed)
{
this._isSubscribed = value;
this.OnSubscriptionChanged();
}
}
}
private SubscriptionBase _subscription;
public string SubscriptionLinkText
{
get { return this._subscription.LinkText; }
}
public Visitor(string name)
{
this.Name = name;
this._isSubscribed = false;
this.OnSubscriptionChanged();
}
private void OnSubscriptionChanged()
{
// Consider also defining an event and raising it here
this._subscription =
SubscriptionBase.GetSubscription(this.IsSubscribed);
}
}
abstract public class SubscriptionBase
{
// Factory method to get instance
static public SubscriptionBase GetSubscription(bool isSubscribed)
{
return isSubscribed ?
new Subscription() as SubscriptionBase
: new NoSubscription() as SubscriptionBase;
}
abstract public string LinkText { get; }
}
public class Subscription : SubscriptionBase
{
public override string LinkText
{
get { return "Today's Special"; }
}
}
public class NoSubscription : SubscriptionBase
{
public override string LinkText
{
get { return "Join now"; }
}
}
I've been studying up on static reflection with LINQ expressions - very cool!
One thought I had - is it possible for one class to 'generate' fields on one class based on static reflection done on another class? I'm thinking specifically of the Builder pattern I've seen here many times. I would like to do a fluent-nhibernate-style property registration that 'generates' fields on the builder that match the class I want to build. Soemthing like this:
public class Color
{
private Color()
{
}
public string Name { get; private set; }
public class Builder : BuilderBase<Color>
{
public Builder()
{
Property(x => x.Name);
}
public Build()
{
return built_up_color;
}
}
}
and support constructor syntax like this:
Color c = new Color.Builder() { Name = "Red" }.Build();
The point of all this is to reduce the number of times I have to repeat defining the properies of Color. I played with this:
public class Color
{
private Color()
{
}
public string Name { get; private set; }
public class Builder
{
private Color _color = new Color();
public string Name
{
get { return _color.Name; }
set { _color.Name = value; }
}
public Build()
{
return _color;
}
}
}
which certainly works AND lists the properties the same # of times but feels wordier and less flexible. It seems like I should be able to do something anonymous-type-y here?
Worth pointing out that Having a class called Color clashing with the System.Drawing.Color is probably a bad idea.
It is very likely to lead to confusion in others (worse still System.Drawring.Color has value semantics whereas your class has reference semantics which can lead to further confusion)
I would point out that what you really want is Named Optional Arguments. I would suggest that putting in cumbersome Builder classes now will be more effort and made it more painful to move to these once you get to c# 4.0. Instead make the constructors that are required (or if need be to avoid type signature collisions static factory methods on the class)
I think it's impossible, you can't generate members except by declaring them explicitly. Bite the bullet and declare a constructor for Color.
PS: I think static reflection is a misnomer, the only thing that's static is the lookup of the member you want to reference — a good thing as far as it goes, but that's not very far.
less code to write but using reflection to set the values.
The trick is to use collection initializers. it is typesafe.
public class Color
{
private Color()
{
}
public string Name { get; private set; }
public int Prop2 { get; private set; }
public class Builder : Builder<Color>
{
public Builder()
{
// possible
_instance.Name = "SomeDefaultValue";
}
}
}
class Builder<T> : IEnumerable<string>
{
protected T _instance = Activator.CreateInstance(typeof(T));
public void Add<TProperty>(Expression<Func<T, TProperty>> prop, TProperty value)
{
StaticReflection.GetPropertyInfo(prop).SetValue(_instance, value, null);
}
public static implicit operator T(Builder<T> builder)
{
return builder.Build();
}
public T Build()
{
return _instance;
}
IEnumerator<string> IEnumerable<string>.GetEnumerator()
{
// e.g. return iterator over the property names
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<string>)this).GetEnumerator();
}
}
and call syntax
var color = new Color.Builder
{
{ x => x.Name, "foo" },
{ x => x.Prop2, 5 }
}.Build();
// or
var color = new Builder<Color>
{
{ x => x.Name, "foo" },
{ x => x.Prop2, 5 }
}.Build();
// or
Color color = new Builder<Color>
{
{ x => x.Name, "foo" },
{ x => x.Prop2, 5 }
};