https://github.com/ufcpp/delegateinterface
https://github.com/ufcpp/delegateinterface
Last synced: 10 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/ufcpp/delegateinterface
- Owner: ufcpp
- License: mit
- Created: 2022-05-27T11:52:32.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2023-01-20T07:48:46.000Z (about 3 years ago)
- Last Synced: 2025-02-01T23:17:49.670Z (12 months ago)
- Language: C#
- Size: 45.9 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# DelegateInterface
## Library usage:
```cs
public interface IA
{
int A(int x);
int B(string x);
(int x, int y) C(TimeSpan x);
P D(P x, P y);
}
```
```cs
using DelegateInterface;
// Create a proxy instance.
var a = Cache.CreateInstance();
// Add delegates to the proxy.
var d = (IDelegateInterface)a;
int factor = 10;
d.Methods["A"] = (int x) => factor * x;
d.Methods["B"] = static (string x) => x.Length;
d.Methods["C"] = new C(1, 2).M;
d.Methods["D"] = static P (P x, P y) => new(x.X + y.X, x.Y + y.Y);
// Invoke interface methods.
Console.WriteLine(a.A(3));
Console.WriteLine(a.B("abc"));
Console.WriteLine(a.C(TimeSpan.FromSeconds(9999)));
Console.WriteLine(a.D(new(2, 3), new(5, 7)));
```
```
30
3
(2, 46)
P { X = 7, Y = 10 }
```
## How it works
`DelegateInterfaceTypeBuilder` class build a proxy class by using `System.Reflection.Emit`.
If you have a interface:
```cs
public interface IA
{
void M1();
string M2();
void M3(TimeSpan x);
int M4(int x, int y);
}
```
The builder class dynamically create a proxy class:
```cs
class IA_Proxy : IDynamicInterface, IA
{
public IDictionary Methods { get; }
public void M1() => Methods["M1"].DynamicInvoke();
public string M2() => (string)Methods["M2"].DynamicInvoke();
public void M3(TimeSpan x) => Methods["M3"].DynamicInvoke(x);
public int M4(int x, int y) => (int)Methods["M4"].DynamicInvoke(x, y);
}
```