Typed dynamic / dynamic type fields #7776
Answered
by
HaloFour
CREAsTIVE
asked this question in
Language Ideas
-
Lets create a simple public class Vector<T> : DynamicObject where T : INumber<T>
{
public T[] values;
public Vector(params T[] values) => this.values = values;
public T Len() => values.Aggregate(T.Zero, (T acc, T v) => acc + v);
// ...
static string fieldNames = "xyzw";
public override bool TryGetMember(GetMemberBinder binder, out object? result)
{
if (base.TryGetMember(binder, out result)) return true;
Vector<T> newVec = new(new T[binder.Name.Length]);
for (int i = 0; i < binder.Name.Length; i++)
newVec.values[i] = values[fieldNames.IndexOf(binder.Name[i])];
result = newVec;
return true;
}
public override string ToString() => $"({string.Join(", ", values)})";
} It uses dynamic v = new Vector<int>(1, 2, 3);
Console.WriteLine(v.xyxy); // (1, 2, 1, 2)
Console.WriteLine(v.xyxy.Len()); 6 The problem is that calling standard methods is accompanied by calling a wrapper. I think this situation needs to be corrected for optimizations and syntax highlighting How it works now: dynamic v = new Vector<int>(1, 2, 3);
v.Len(); // Vector<int>.TryGetMember("Len", new object)()
v.xyxz; // Vector<int>.TryGetMember("xyxz", new object) I wanna see syntax like this: (typed dynamic) dynamic<Vector<int>> v = new Vector<int>(1, 2, 3);
v.Len(); // Vector<int>.Len
v.xyxz; // Vector<int>.TryGetMember("xyxz", new object) Or maybe just convert non-existent method calls to Vector<int> v = new Vector<int>(1, 2, 3);
v.Len(); // Normal Vector<int>.Len
v.xyxz; // Redirect call to TryGetMember |
Beta Was this translation helpful? Give feedback.
Answered by
HaloFour
Dec 19, 2023
Replies: 1 comment
-
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
svick
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See: #1678 #1116 #969 #284