if (Regex.IsMatch(stringToCheck, @"\p{IsCyrillic}"))
{
// there is at least one cyrillic character in the string
}
public interface IParam
{
}
public interface IProcessor
{ }
public interface IProcessor<in T>: IProcessor
where T : IParam
{
public void Apply(T param);
}
public class ConcreteProcessorA : IProcessor<ConcreteParamA>
{
public void Apply(ConcreteParamA param)
{
Console.WriteLine("Hello from processor A");
}
}
public class ConcreteParamA : IParam
{
}
public class ConcreteProcessorB : IProcessor<ConcreteParamB>
{
public void Apply(ConcreteParamB param)
{
Console.WriteLine("hello form ProcessorB");
}
}
public class ConcreteParamB : IParam
{
}
public class Provider
{
public Provider(IEnumerable<IProcessor> processors)
{
_processors = processors.ToList();
}
private List<IProcessor> _processors;
public void Apply<TParam>(TParam param) where TParam: IParam
{
foreach (var processor in _processors.Where(p => p
.GetType()
.GetInterfaces()
.Any(i => i.IsAssignableTo(typeof(IProcessor<TParam>))))
.Cast<IProcessor<TParam>>())
{
processor.Apply(param);
}
throw new InvalidOperationException("Для переданного типа нет обработчика");
}
}
public class Program
{
static void Main(string[] args)
{
var provider = new Provider(new IProcessor[]
{
new ConcreteProcessorA()
});
provider.Apply(new ConcreteParamA());
try
{
provider.Apply(new ConcreteParamB());
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
Hello from processor Aзатем пишет исключение, т.к. обработчика не нашлось
public class MyEvent
{
public event EventHandler ActionHappened;
public void FireEvent()
{
ActionHappened?.Invoke(this, EventArgs.Empty);
}
}
public class SomeClass
{
public void RegisterInner(MyEvent @event)
{
EventHandler handler = null!;
handler = (sender, args) =>
{
Console.WriteLine("Hello, world");
@event.ActionHappened -= handler;
};
@event.ActionHappened += handler;
}
}
public class Program
{
public static void Main()
{
var myEvent = new MyEvent();
var someClass = new SomeClass();
someClass.RegisterInner(myEvent);
myEvent.FireEvent();
myEvent.FireEvent();
myEvent.FireEvent();
myEvent.FireEvent();
myEvent.FireEvent();
}
}