Creating objects with reflection - c#

I'm trying to write a NullObject creation method, where I pass in a class name that implements an ICreateEmptyInstance interface (that is empty) and it walks it's properties looking for other classes that implement ICreateEmptyInstance and will create "Null" instances of those.
public interface ICreateEmptyInstance { }
public static class NullObject
{
public static T Create<T>() where T : ICreateEmptyInstance, new()
{
var instance = new T();
var properties = typeof(T).GetProperties();
foreach (var property in properties.Where(property => typeof(ICreateEmptyInstance).IsAssignableFrom(property.PropertyType)))
{
var propertyInstance = NullObject.Create<property.PropertyType>();
property.SetValue(instance, propertyInstance);
}
return instance;
}
}
I should be able to call it with this
var myEmptyClass = NullObject.Create<MyClass>();
Where I'm having issues is inside of the foreach loop, with this line
var propertyInstance = NullObject.Create<property.PropertyType>();
...obviously that doesn't work, but how can I accomplish creating a "null object" to assign to the instance I'm currently creating.
EDIT:
And what about generics?? I'd like empty instances created
foreach (var property in properties.Where(property => property.GetType().IsGenericType))
{
var propertyInstance = Enumerable.Empty<>(); //TODO: how do I get the type for here?
property.SetValue(instance, propertyInstance);
}

You can create a non-generic method and use it:
public static T Create<T>() where T : ICreateEmptyInstance, new()
{
return (T) Create(typeof (T));
}
private static object Create(Type type)
{
var instance = Activator.CreateInstance(type);
var properties = type.GetProperties();
foreach (var property in properties.Where(property => typeof(ICreateEmptyInstance).IsAssignableFrom(property.PropertyType)))
{
var propertyInstance = NullObject.Create(property.PropertyType);
property.SetValue(instance, propertyInstance);
}
return instance;
}

Related

How to conditionally create obj with constraints

I have 2 class which has a different constraint, and I want to create obj for them conditionally in a generic function. Example below.
public class Foo1<T>
where T : class, Interface1, new()
{
// do sth...
}
public class Foo2<T>
where T : class, Interface2, new()
{
//do sth...
}
public static void Create<T>()
{
if(typeof(Interface1).IsAssignableFrom(typeof(T))
{
var obj = new Foo1();
//...
} else if (typeof(Interface2).IsAssignableFrom(typeof(T))
{
var obj = new Foo1();
//...
}
}
And I got the error "There is no implicit reference conversion from T to Interface1/2".
The problem is similar to Similiar to How to conditionally invoke a generic method with constraints?, but I can find a place to add (dynamic).
You can create an instance of a generic class using reflection.
public static void Create<T>()
{
if (typeof(Interface1).IsAssignableFrom(typeof(T)))
{
var d1 = typeof(Foo1<>);
Type[] typeArgs = { typeof(T) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);
}
else if (typeof(Interface2).IsAssignableFrom(typeof(T))
{
// same for Foo2
}
}

How to use a superclass method using reflections C#

I have a bunch of classes that inherit from a single class. I'm using reflections to access the classes, since the ones that will be accessed will change in runtime.
But I am having some trouble when trying to invoke a method declared at superclass.
Here is my parent class:
public class ParentClass {
public ParentClass (Type type) {
}
public string method0String () {
return string;
}
public void method1Void (string) {
}
}
Here is my child class:
public class ChildClass : ParentClass {
public ParentClass () : base(typeof(ChildClass)) {
}
}
Here is the abstract class code where I cast the methods:
Type childType = Type.GetType(className[i]);
ConstructorInfo childConstructor = childType.GetConstructor(new Type[0]);
object childObject = null;
childObject = childConstructor.Invoke(childObject, new object[0]);
MethodInfo parentMethod0String = childType.GetMethod("method0String");
MethodInfo parentMethod1Void = childType.GetMethod("method1Void");
parentMethod1Void.Invoke(childObject, new object[]{argString});
object finalString = parentMethod0String.Invoke(childObject, new object[0]);
The MethodInfos are always null, which causes this error when I try to invoke them:
System.NullReferenceException: Object reference not set to an instance of an object
I haven't found anyway around this.
Basically, I just need to invoke a super method using the child as the dynamic object. How can I achieve this?
#Edit
After #nvoigt answer, my code looks like this:
Type childType = Type.GetType(className[i]);
object childObject = Activator.CreateInstance(childType);
Type parentType = Type.GetType("ParentClass");
MethodInfo parentMethod0String = parentType.GetMethod("method0String");
MethodInfo parentMethod1Void = parentType.GetMethod("method1Void");
parentMethod1Void.Invoke(childObject, new object[]{argString});
object finalString = parentMethod0String.Invoke(childObject, new object[0]);
And the error is a little different:
System.Reflection.TargetException: Object does not match target type.
You can do it this way:
namespace StackOverFlowTest
{
using System;
class BaseClass
{
public int BaseClassMethod(int x)
{
return x * x;
}
}
class DerivedClass : BaseClass
{
}
class Program
{
static void Main()
{
var derivedType = typeof(DerivedClass);
var baseType = typeof(BaseClass);
var method = baseType.GetMethod("BaseClassMethod");
var derivedInstance = Activator.CreateInstance(derivedType);
var result = method.Invoke(derivedInstance, new object[] { 42 });
Console.WriteLine(result);
Console.ReadLine();
}
}
}

Add intellisense when writing lambda's for an Action<dynamic>

This question is related to this other question.
I have the following method:
public static T GetNewData<T>(params Action<dynamic>[] actions) where T : class, new()
{
dynamic dynamicData = new DeepObject();
foreach (var action in actions)
{
action(dynamicData);
}
return Converter.Convert<T>(dynamicData);
}
The users of this method will include less technical people, even non-developers and as such the easier writing calls to this method is the better. My sticking point right now is that by using Action<dynamic> as the parameter type there is no intellisense provided to the user. In the context I know that the intellisense should be acting as if the dynamic was in fact T.
So is their a way I could either: Tell Visual Studio to use type T for the intellisense or change the parameter to be Action<T> and somehow programmatically change it to be Action<dynamic> or Action<DeepObject> so that the call to it will succeed?
EDIT: To clarify, the types that I am using for T are not of type DeepObject and they do not inherit any standard interface, the use of DeepObject is to allow setting up nested types without the user needing to explicitly instantiate at each level. This was the original usage before adding the dynamic and DeepObject code:
ExampleDataFactory.GetNewData<ServicesAndFeaturesInfo>(
x => x.Property1 = ExampleDataFactory.GetNewData<Property1Type>(),
x => x.Property1.Property2 = ExampleDataFactory.GetNewData<Property2Type>(),
x => x.Property1.Property2.Property3 = ExampleDataFactory.GetNewData<Property3Type>(),
x => x.Property1.Property2.Property3.Property4 = true);
Here is what it looks like now:
ExampleDataFactory.GetNewData<ServicesAndFeaturesInfo>(
x => x.Property1.Property2.Property3.Property4 = true);
EDIT: Here is the fully implemented solution based on nmclean's answer
public static DataBuilder<T> GetNewData<T>() where T : class, new()
{
return new DataBuilder<T>();
}
The DataBuilder Class:
public class DataBuilder<T>
{
public readonly T data;
public DataBuilder()
{
data = Activator.CreateInstance<T>();
}
public DataBuilder(T data)
{
this.data = data;
}
public DataBuilder<T> SetValue<T2>(Expression<Func<T, T2>> expression, T2 value)
{
var mExpr = GetMemberExpression(expression);
var obj = Recurse(mExpr);
var p = (PropertyInfo)mExpr.Member;
p.SetValue(obj, value);
return this;
}
public T Build()
{
return data;
}
public object Recurse(MemberExpression expr)
{
if (expr.Expression.Type != typeof(T))
{
var pExpr = GetMemberExpression(expr.Expression);
var parent = Recurse(pExpr);
var pInfo = (PropertyInfo) pExpr.Member;
var obj = pInfo.GetValue(parent);
if (obj == null)
{
obj = Activator.CreateInstance(pInfo.PropertyType);
pInfo.SetValue(parent, obj);
}
return obj;
}
return data;
}
private static MemberExpression GetMemberExpression(Expression expr)
{
var member = expr as MemberExpression;
var unary = expr as UnaryExpression;
return member ?? (unary != null ? unary.Operand as MemberExpression : null);
}
private static MemberExpression GetMemberExpression<T2>(Expression<Func<T, T2>> expr)
{
return GetMemberExpression(expr.Body);
}
}
The Usage:
ExampleDataFactory.GetNewData<ServicesAndFeaturesInfo>()
.SetValue(x=> x.Property1.EnumProperty, EnumType.Own)
.SetValue(x=> x.Property2.Property3.Property4.BoolProperty, true)
.Build();
Do not use Action<dynamic>, use Action<T>with method's constraint where T:DeepObject. Users will get intellisence and ability to use strongly typed objects:
public static DeepObject GetNewData<T>(params Action<T>[] actions)
where T : DeepObject, //restrict user only inheritors of DeepObject
new() //and require constructor
{
var data = new T();
foreach (var action in actions)
{
action(data);
}
return data;
}
Does the user need to access unknown properties or add new ones? If not, using dynamic objects seems like a step backwards. If your desired syntax does compile as an Action<T>, I think you should just declare it that way and then go with your first instinct of using the LINQ Expression API to decide how to interpret the code.
Unfortunately, although statements, such as an assignment, are part of the API, C# doesn't support converting them to expression trees. This is not allowed:
public static T GetNewData<T>(params Expression<Action<T>>[] actions)
where T : class, new() {
...
}
...
ExampleDataFactory.GetNewData<ServicesAndFeaturesInfo>(
x => x.Property1.Property2.Property3.Property4 = true);
Only single-line expressions that would have a return a value are supported. So I think the best you could do is something like this:
public class Assignment<T> {
public readonly Expression Expression;
public readonly object Value;
public Assignment(Expression<Func<T, object>> expression, object value) {
Expression = expression;
Value = value;
}
}
...
public static T GetNewData<T>(params Assignment<T>[] assignments)
where T : class, new() {
var data = Activator.CreateInstance<T>();
foreach (var assignment in assignments) {
// todo:
// - pull property names from assignment.Expression
// - initialize nested properties / assign to assignment.Value
}
return data;
}
...
ExampleDataFactory.GetNewData<ServicesAndFeaturesInfo>(
new Assignment<ServicesAndFeaturesInfo>(
x => x.Property1.Property2.Property3.Property4, true));
Getting the property names from an expression tree of chained property access is not too complicated. Here is one implementation.
Of course, the new Assignment<ServicesAndFeaturesInfo>(...) is ugly and repetitive, so maybe it could be restructured to something like this:
var newData = ExampleDataFactory.NewData<ServicesAndFeaturesInfo>();
newData.Add(x => x.Property1.Property2.Property3.Property4, true);
newData.Add(...);
...
newData.Get();

Refelection Converting Property into another instance

i am trying to "upcast" a Entity. The Entity B have just a few more propeties.
Entities:
public class A
{
public String Name { get; set; }
}
public class B : A
{
public String ForeName { get; set; }
}
I am trying to conver the value of A.Name into B.Name programmatically.
I´ve written a little function for that case:
public static T Upcast<T>(Type typeOf, Object obj) where T : new()
{
var target = new T();
var props = obj.GetType().GetProperties();
var targetProps = target.GetType().GetProperties();
foreach (var prop in props)
{
foreach (var tp in targetProps)
{
if (prop.Name.Equals(tp.Name))
{
var val = prop.GetValue(props, null);
tp.SetValue(null, val, null);
}
}
}
return target;
}
In this case: my target is class B and my obj is class A
But it fires a Exception in the second loop:
var val = prop.GetValue(props, null);
The Exception "Object does not match target type".
i am calling the function on a normal way:
static void Main(string[] args)
{
var a = new A {Name = "Smith"};
var resp = Upcast<B>(a.GetType(), a);
Console.ReadLine();
}
Replace prop.GetValue(props, null); with prop.GetValue(obj, null);
It gives me "Smith".
You must call prop.GetValue(...); with the target object as argument, not with the property collection:
prop.GetValue(obj, null);
Starting with .NET 4.5 you can write
var val = prop.GetValue(obj);
You are trying the read the value out of an instance of PropertyInfo class. But what you want is to read the value out of your instance of A.
Another hint, for cleaner code:
Don't pass the type of A as argument. If you pass an instance of A, your method can make obj.GetType().
But: why are you doing that???

Create instance of generic type whose constructor requires a parameter?

If BaseFruit has a constructor that accepts an int weight, can I instantiate a piece of fruit in a generic method like this?
public void AddFruit<T>()where T: BaseFruit{
BaseFruit fruit = new T(weight); /*new Apple(150);*/
fruit.Enlist(fruitManager);
}
An example is added behind comments. It seems I can only do this if I give BaseFruit a parameterless constructor and then fill in everything through member variables. In my real code (not about fruit) this is rather impractical.
-Update-
So it seems it can't be solved by constraints in any way then. From the answers there are three candidate solutions:
Factory Pattern
Reflection
Activator
I tend to think reflection is the least clean one, but I can't decide between the other two.
Additionally a simpler example:
return (T)Activator.CreateInstance(typeof(T), new object[] { weight });
Note that using the new() constraint on T is only to make the compiler check for a public parameterless constructor at compile time, the actual code used to create the type is the Activator class.
You will need to ensure yourself regarding the specific constructor existing, and this kind of requirement may be a code smell (or rather something you should just try to avoid in the current version on c#).
You can't use any parameterised constructor. You can use a parameterless constructor if you have a "where T : new()" constraint.
It's a pain, but such is life :(
This is one of the things I'd like to address with "static interfaces". You'd then be able to constrain T to include static methods, operators and constructors, and then call them.
Yes; change your where to be:
where T:BaseFruit, new()
However, this only works with parameterless constructors. You'll have to have some other means of setting your property (setting the property itself or something similar).
Most simple solution
Activator.CreateInstance<T>()
As Jon pointed out this is life for constraining a non-parameterless constructor. However a different solution is to use a factory pattern. This is easily constrainable
interface IFruitFactory<T> where T : BaseFruit {
T Create(int weight);
}
public void AddFruit<T>( IFruitFactory<T> factory ) where T: BaseFruit {
BaseFruit fruit = factory.Create(weight); /*new Apple(150);*/
fruit.Enlist(fruitManager);
}
Yet another option is to use a functional approach. Pass in a factory method.
public void AddFruit<T>(Func<int,T> factoryDel) where T : BaseFruit {
BaseFruit fruit = factoryDel(weight); /* new Apple(150); */
fruit.Enlist(fruitManager);
}
You can do by using reflection:
public void AddFruit<T>()where T: BaseFruit
{
ConstructorInfo constructor = typeof(T).GetConstructor(new Type[] { typeof(int) });
if (constructor == null)
{
throw new InvalidOperationException("Type " + typeof(T).Name + " does not contain an appropriate constructor");
}
BaseFruit fruit = constructor.Invoke(new object[] { (int)150 }) as BaseFruit;
fruit.Enlist(fruitManager);
}
EDIT: Added constructor == null check.
EDIT: A faster variant using a cache:
public void AddFruit<T>()where T: BaseFruit
{
var constructor = FruitCompany<T>.constructor;
if (constructor == null)
{
throw new InvalidOperationException("Type " + typeof(T).Name + " does not contain an appropriate constructor");
}
var fruit = constructor.Invoke(new object[] { (int)150 }) as BaseFruit;
fruit.Enlist(fruitManager);
}
private static class FruitCompany<T>
{
public static readonly ConstructorInfo constructor = typeof(T).GetConstructor(new Type[] { typeof(int) });
}
As an addition to user1471935's suggestion:
To instantiate a generic class by using a constructor with one or more parameters, you can now use the Activator class.
T instance = Activator.CreateInstance(typeof(T), new object[] {...})
The list of objects are the parameters you want to supply. According to Microsoft:
CreateInstance [...] creates an instance of the specified type using the constructor that best matches the specified parameters.
There's also a generic version of CreateInstance (CreateInstance<T>()) but that one also does not allow you to supply constructor parameters.
I created this method:
public static V ConvertParentObjToChildObj<T,V> (T obj) where V : new()
{
Type typeT = typeof(T);
PropertyInfo[] propertiesT = typeT.GetProperties();
V newV = new V();
foreach (var propT in propertiesT)
{
var nomePropT = propT.Name;
var valuePropT = propT.GetValue(obj, null);
Type typeV = typeof(V);
PropertyInfo[] propertiesV = typeV.GetProperties();
foreach (var propV in propertiesV)
{
var nomePropV = propV.Name;
if(nomePropT == nomePropV)
{
propV.SetValue(newV, valuePropT);
break;
}
}
}
return newV;
}
I use that in this way:
public class A
{
public int PROP1 {get; set;}
}
public class B : A
{
public int PROP2 {get; set;}
}
Code:
A instanceA = new A();
instanceA.PROP1 = 1;
B instanceB = new B();
instanceB = ConvertParentObjToChildObj<A,B>(instanceA);
You can use the following command:
T instance = (T)typeof(T).GetConstructor(new Type[0]).Invoke(new object[0]);
Be sure to see the following
reference.
Recently I came across a very similar problem. Just wanted to share our solution with you all. I wanted to I created an instance of a Car<CarA> from a json object using which had an enum:
Dictionary<MyEnum, Type> mapper = new Dictionary<MyEnum, Type>();
mapper.Add(1, typeof(CarA));
mapper.Add(2, typeof(BarB));
public class Car<T> where T : class
{
public T Detail { get; set; }
public Car(T data)
{
Detail = data;
}
}
public class CarA
{
public int PropA { get; set; }
public CarA(){}
}
public class CarB
{
public int PropB { get; set; }
public CarB(){}
}
var jsonObj = {"Type":"1","PropA":"10"}
MyEnum t = GetTypeOfCar(jsonObj);
Type objectT = mapper[t]
Type genericType = typeof(Car<>);
Type carTypeWithGenerics = genericType.MakeGenericType(objectT);
Activator.CreateInstance(carTypeWithGenerics , new Object[] { JsonConvert.DeserializeObject(jsonObj, objectT) });
If you are willing to use a c# precompiler, you could resolve this so that it does have compile time constraints:
// Used attribute
[AttributeUsage(AttributeTargets.Parameter)]
class ResolvedAsAttribute : Attribute
{
public string Expression;
public ResolvedAsAttribute(string expression)
{
this.Expression = expression;
}
}
// Fruit manager source:
class FruitManager {
...
public void AddFruit<TFruit>([ResolvedAs("(int p) => new TFruit(p)")] Func<int,TFruit> ctor = null)where TFruit: BaseFruit{
BaseFruit fruit = ctor(weight); /*new Apple(150);*/
fruit.Enlist(fruitManager);
}
}
// Fruit user source:
#ResolveInclude ../Managers/FruitManager.cs
...
fruitManager.AddFruit<Apple>();
...
Your precompiler would then turn the Fruit user source into:
...
fruitManager.AddFruit<Apple>((int p) => new Apple(p));
...
Using Roslyn, your precompiler could look something like this (here is room for improvement):
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using System.Threading;
using System.Text.RegularExpressions;
public class CsResolveIncludeAnalyser : CSharpSyntaxWalker
{
private List<(string key, MethodDeclarationSyntax node)> methodsToResolve = new List<(string key, MethodDeclarationSyntax node)>();
public List<(string key, MethodDeclarationSyntax node)> Analyse(string source)
{
var tree = CSharpSyntaxTree.ParseText(source);
var syntaxRoot = tree.GetRoot();
Visit(tree.GetRoot());
return methodsToResolve;
}
public override void VisitMethodDeclaration(MethodDeclarationSyntax methodDeclaration)
{
base.VisitMethodDeclaration(methodDeclaration);
if (methodDeclaration.ParameterList.Parameters.Count > 0)
{
foreach (var parm in methodDeclaration.ParameterList.Parameters)
{
var parmHasResolvedAs = parm.AttributeLists.Where((el) => el.Attributes.Where((attr) => attr.Name is IdentifierNameSyntax && ((IdentifierNameSyntax)attr.Name).Identifier.Text.Contains("ResolvedAs")).Any()).Any();
if (parmHasResolvedAs)
{
var name = methodDeclaration.Identifier.ValueText;
methodsToResolve.Add((name, methodDeclaration));
return;
}
}
}
}
}
public class CsSwiftRewriter : CSharpSyntaxRewriter
{
private string currentFileName;
private bool withWin32ErrorHandling;
private Dictionary<string,MethodDeclarationSyntax> methodsToResolve = new Dictionary<string, MethodDeclarationSyntax>();
private Dictionary<string, MethodDeclarationSyntax> getMethodsToResolve(string source, string fileName)
{
Dictionary<string, MethodDeclarationSyntax> methodsToResolve = new Dictionary<string, MethodDeclarationSyntax>();
var path = Path.GetDirectoryName(fileName);
var lines = source.Split(new[] { '\r', '\n' });
var resolveIncludes = (from el in lines where el.StartsWith("#ResolveInclude") select el.Substring("#ResolveInclude".Length).Trim()).ToList();
var analyser = new CsResolveIncludeAnalyser();
foreach (var resolveInclude in resolveIncludes)
{
var src = File.ReadAllText(path + "/" + resolveInclude);
var list = analyser.Analyse(src);
foreach (var el in list)
{
methodsToResolve.Add(el.key, el.node);
}
}
return methodsToResolve;
}
public static string Convert(string source, string fileName)
{
return Convert(source, fileName, false);
}
public static string Convert(string source, string fileName, bool isWithWin32ErrorHandling)
{
var rewriter = new CsSwiftRewriter() { currentFileName = fileName, withWin32ErrorHandling = isWithWin32ErrorHandling };
rewriter.methodsToResolve = rewriter.getMethodsToResolve(source, fileName);
var resolveIncludeRegex = new Regex(#"(\#ResolveInclude)\b");
source = resolveIncludeRegex.Replace(source, "//$1");
var tree = CSharpSyntaxTree.ParseText(source);
var syntaxRoot = tree.GetRoot();
var result = rewriter.Visit(tree.GetRoot());
return "#line 1 \"" + Path.GetFileName(fileName) + "\"\r\n" + result.ToFullString();
}
internal List<string> transformGenericArguments(List<string> arguments, GenericNameSyntax gName, TypeParameterListSyntax typeParameterList)
{
var res = new List<string>();
var typeParameters = typeParameterList.ChildNodes().ToList();
foreach (var argument in arguments)
{
var arg = argument;
for (int i = 0; i < gName.TypeArgumentList.Arguments.Count; i++)
{
var key = typeParameters[i];
var replacement = gName.TypeArgumentList.Arguments[i].ToString();
var regex = new System.Text.RegularExpressions.Regex($#"\b{key}\b");
arg = regex.Replace(arg, replacement);
}
res.Add(arg);
}
return res;
}
const string prefix = "";
internal List<string> extractExtraArguments(MethodDeclarationSyntax methodDeclaration)
{
var res = new List<String>();
foreach (var parm in methodDeclaration.ParameterList.Parameters)
{
foreach (var attrList in parm.AttributeLists)
{
foreach (var attr in attrList.Attributes)
{
if (attr.Name is IdentifierNameSyntax && string.Compare(((IdentifierNameSyntax)attr.Name).Identifier.Text, "ResolvedAs") == 0)
{
var programmCode = attr.ArgumentList.Arguments.First().ToString().Trim();
var trimmedProgrammCode = (programmCode.Length >= 2 && programmCode[0] == '"' && programmCode[programmCode.Length - 1] == '"') ? programmCode.Substring(1, programmCode.Length - 2) : programmCode;
res.Add(prefix + parm.Identifier.Text + ":" + trimmedProgrammCode);
}
}
}
}
return res;
}
internal List<string> extractExtraArguments(MethodDeclarationSyntax methodDeclaration, SimpleNameSyntax name)
{
var arguments = extractExtraArguments(methodDeclaration);
if (name != null && name is GenericNameSyntax)
{
var gName = name as GenericNameSyntax;
return transformGenericArguments(arguments, gName, methodDeclaration.TypeParameterList);
}
return arguments;
}
public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax c_expressionStatement)
{
InvocationExpressionSyntax expressionStatement = (InvocationExpressionSyntax) base.VisitInvocationExpression(c_expressionStatement);
List<string> addedArguments = null;
switch (expressionStatement.Expression)
{
case MemberAccessExpressionSyntax exp:
if (methodsToResolve.ContainsKey(exp.Name?.Identifier.ValueText))
{
addedArguments = extractExtraArguments(methodsToResolve[exp.Name.Identifier.ValueText], exp.Name);
}
break;
case GenericNameSyntax gName:
if (methodsToResolve.ContainsKey(gName.Identifier.ValueText))
{
addedArguments = extractExtraArguments(methodsToResolve[gName.Identifier.ValueText], gName);
}
break;
default:
var name = (from el in expressionStatement.ChildNodes()
where el is GenericNameSyntax
select (el as GenericNameSyntax)).FirstOrDefault();
if (name != default(GenericNameSyntax))
{
if (methodsToResolve.ContainsKey(name.Identifier.ValueText))
{
addedArguments = extractExtraArguments(methodsToResolve[name.Identifier.ValueText], name);
}
}
break;
}
if (addedArguments?.Count > 0)
{
var addedArgumentsString = string.Join(",", addedArguments);
var args = expressionStatement.ArgumentList.ToFullString();
var paras = $"({(expressionStatement.ArgumentList.Arguments.Count > 0 ? string.Join(",", args.Substring(1,args.Length - 2), addedArgumentsString) : addedArgumentsString)})" ;
var argList = SyntaxFactory.ParseArgumentList(paras);
return expressionStatement.WithArgumentList(argList);
}
return expressionStatement;
}
}
The Precompiler could be called using a T4 script, optionally regenerating the source at compile time.
It is still possible, with high performance, by doing the following:
//
public List<R> GetAllItems<R>() where R : IBaseRO, new() {
var list = new List<R>();
using ( var wl = new ReaderLock<T>( this ) ) {
foreach ( var bo in this.items ) {
T t = bo.Value.Data as T;
R r = new R();
r.Initialize( t );
list.Add( r );
}
}
return list;
}
and
//
///<summary>Base class for read-only objects</summary>
public partial interface IBaseRO {
void Initialize( IDTO dto );
void Initialize( object value );
}
The relevant classes then have to derive from this interface and initialize accordingly.
Please note, that in my case, this code is part of a surrounding class, which already has <T> as generic parameter.
R, in my case, also is a read-only class. IMO, the public availability of Initialize() functions has no negative effect on the immutability. The user of this class could put another object in, but this would not modify the underlying collection.

Categories