Existe uma maneira de “substituir” um método pela reflexão?
-
13-12-2019 - |
Pergunta
Sem herdar mas apenas com reflexão é possível alterar dinamicamente o código de um método em C#?
algo como :
nameSpaceA.Foo.method1 = aDelegate;
Não consigo alterar/editar a classe Foo.
namespace nameSpaceA
{
class Foo
{
private void method1()
{
// ... some Code
}
}
}
Meu objetivo final é alterar dinamicamente o código de:
public static IList<XPathNavigator> EnsureNodeSet(IList<XPathItem> listItems);
Em System.Xml.Xsl.Runtime.XslConvert.cs
virar :
if (!item.IsNode)
throw new XslTransformException(Res.XPath_NodeSetExpected, string.Empty);
em :
if (!item.IsNode)
throw new XslTransformException(Res.XPath_NodeSetExpected, item.value);
Solução
A primeira parte dessa resposta está errada, só estou deixando para que a evolução nos comentários faça sentido.Por favor, veja as EDIÇÕES.
Você não está procurando reflexão, mas emissão (que é o contrário).
Em particular, existe um método que faz exatamente o que você deseja, sorte sua!
Ver TypeBuilder.DefineMethodOverride
EDITAR:
Escrevendo esta resposta, acabei de lembrar disso remixar permite que você faça isso também.É muito mais difícil.
Re-mix é um framework que “simula” mixins em C#.Em seu aspecto básico, você pode pensar nisso como interfaces com implementações padrão.Se você for mais longe, será muito mais do que isso.
EDITAR 2: Aqui está um exemplo de uso para remixar (implementar INotifyPropertyChanged em uma classe que não oferece suporte e não tem ideia de mixins).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Remotion.Mixins;
using System.ComponentModel;
using MixinTest;
[assembly: Mix(typeof(INPCTester), typeof(INotifyPropertyChangedMixin))]
namespace MixinTest
{
//[Remotion.Mixins.CompleteInterface(typeof(INPCTester))]
public interface ICustomINPC : INotifyPropertyChanged
{
void RaisePropertyChanged(string prop);
}
//[Extends(typeof(INPCTester))]
public class INotifyPropertyChangedMixin : Mixin<object>, ICustomINPC
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string prop)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(prop));
}
}
}
public class ImplementsINPCAttribute : UsesAttribute
{
public ImplementsINPCAttribute()
: base(typeof(INotifyPropertyChangedMixin))
{
}
}
//[ImplementsINPC]
public class INPCTester
{
private string m_Name;
public string Name
{
get { return m_Name; }
set
{
if (m_Name != value)
{
m_Name = value;
((ICustomINPC)this).RaisePropertyChanged("Name");
}
}
}
}
public class INPCTestWithoutMixin : ICustomINPC
{
private string m_Name;
public string Name
{
get { return m_Name; }
set
{
if (m_Name != value)
{
m_Name = value;
this.RaisePropertyChanged("Name");
}
}
}
public void RaisePropertyChanged(string prop)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(prop));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
E o teste:
static void INPCImplementation()
{
Console.WriteLine("INPC implementation and usage");
var inpc = ObjectFactory.Create<INPCTester>(ParamList.Empty);
Console.WriteLine("The resulting object is castable as INPC: " + (inpc is INotifyPropertyChanged));
((INotifyPropertyChanged)inpc).PropertyChanged += inpc_PropertyChanged;
inpc.Name = "New name!";
((INotifyPropertyChanged)inpc).PropertyChanged -= inpc_PropertyChanged;
Console.WriteLine();
}
static void inpc_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine("Hello, world! Property's name: " + e.PropertyName);
}
//OUTPUT:
//INPC implementation and usage
//The resulting object is castable as INPC: True
//Hello, world! Property's name: Name
Observe que:
[assembly: Mix(typeof(INPCTester), typeof(INotifyPropertyChangedMixin))]
e
[Extends(typeof(INPCTester))] //commented out in my example
e
[ImplementsINPC] //commented out in my example
Tenha exatamente o mesmo efeito.É uma questão de onde você deseja definir que um mixin específico será aplicado a uma classe específica.
Exemplo 2:substituindo Equals e GetHashCode
public class EquatableByValuesMixin<[BindToTargetType]T> : Mixin<T>, IEquatable<T> where T : class
{
private static readonly FieldInfo[] m_TargetFields = typeof(T).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
bool IEquatable<T>.Equals(T other)
{
if (other == null)
return false;
if (Target.GetType() != other.GetType())
return false;
for (int i = 0; i < m_TargetFields.Length; i++)
{
object thisFieldValue = m_TargetFields[i].GetValue(Target);
object otherFieldValue = m_TargetFields[i].GetValue(other);
if (!Equals(thisFieldValue, otherFieldValue))
return false;
}
return true;
}
[OverrideTarget]
public new bool Equals(object other)
{
return ((IEquatable<T>)this).Equals(other as T);
}
[OverrideTarget]
public new int GetHashCode()
{
int i = 0;
foreach (FieldInfo f in m_TargetFields)
i ^= f.GetValue(Target).GetHashCode();
return i;
}
}
public class EquatableByValuesAttribute : UsesAttribute
{
public EquatableByValuesAttribute()
: base(typeof(EquatableByValuesMixin<>))
{
}
}
Esse exemplo é minha implementação do laboratório prático fornecido com remix.Você pode encontrar mais informações lá.