How to get special MemberInfo of List<> - c#

Below is code fragments
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace DetailTest
{
class Program
{
static void Main(string[] args)
{
A a = new A();
PropertyInfo pi = a.GetType().GetProperty("cs");
MemberInfo[] mis = pi.PropertyType.GetMembers();
MemberInfo[] mis2 = mis.Where(d => d.Name.StartsWith("A")).ToArray();
foreach (MemberInfo mi in mis2)
{
Console.WriteLine(mi);
}
}
}
class A
{
B _b = new B();
public B b { get{return _b;}}
public List<C> cs{get;set;}
}
}
I just want to get Any method, but I got nothing. Why?
I mean how to get Any method of List type?
ps: I really reference System.Linq

Related

how to using FindAll to get List in c#

Hi Everyone sorry i have a question, i have a simple code to get cheaper books from a list, i use one class book with properties, one class to set the books to the list and one main program. here is the book class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AdvanceCSHarpLambda
{
public class Book
{
public string Title { get; set; }
public int Price { get; set; }
}
}
and here the BookRepository class (List)
using System;
using System.Collections.Generic;
namespace AdvanceCSHarpLambda
{
public class BookRepository
{
public List<Book> GetBooks()
{
return new List<Book>
{
new Book() {Title="T1", Price=1 },
new Book() {Title="T2", Price=2 },
new Book() {Title="T3", Price=3 }
};
}
}
}
and here the main program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AdvanceCSHarpLambda
{
class Program
{
static void Main(string[] args)
{
var books = new BookRepository();
var cheapBooks = books.FindAll(bookCheaper);
foreach (var book in cheapBooks)
{
Console.WriteLine(book.Title);
}
}
static bool bookCheaper(Book book)
{
return book.Price < 10;
}
}
}
the problem is i got red line in books.FindAll(bookCheaper), any one can help me whats going on in this redline? thx before
You need to call GetBooks
books.GetBooks().FindAll(bookCheaper)
Your books should be a List, not BookRepository.
You need a Predicate for the FindAll function.
books.FindAll(x=>x.Price < 3)
Something like this.

Dynamic object doesn't contain a definition for a property from a reference

The error I got :
"object" doesn't contain a definition for "test"
I also tried game.test() but I keep getting this error
This solution is divided in two distinct projects :
The first one is a .dll
The second one is a console
the goal is to call the get method from the 'iw4mp' class dynamicaly. So I would be able to call any from the class while it will be loaded.
the COD class should look useless but in the futur it will look if the process is running on the computer but for my test I use a string (but it actually work same way as if it was looking for a process).
Code from the DLL
COD
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CODOffsets.Interface;
using CODOffsets.Offsets;
namespace CODOffsets
{
public class COD
{
static string[] games = { "iw4mp", "iw5mp", "bo1" };
static Type CallofDuty;
public static bool checkGame()
{
foreach (string game in games)
{
if (ProcessHandle(game))
{
CallofDuty = Type.GetType("CODOffsets.Offsets" + "." + game);
return true;
}
}
return false;
}
public static object Game()
{
return Activator.CreateInstance(CallofDuty) as ICODClass;
}
public static bool ProcessHandle(string game)
{
if (game == "iw4mp")
return true;
else
return false;
}
}
}
Interface
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CODOffsets.Interface
{
interface ICODClass
{
string test { get; }
}
}
Offset
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CODOffsets.Interface;
namespace CODOffsets.Offsets
{
class iw4mp : ICODClass
{
public string test { get { return "this is mw2"; } }
}
}
Code from the Console project
Main
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CODOffsets;
namespace TestGenericClass
{
class Program
{
static void Main(string[] args)
{
if (COD.checkGame())
{
dynamic game = COD.Game();
Console.WriteLine(game.test);
Console.ReadKey();
}
}
}
}
It should basically work as the way you did. But, if not so, here are some alternatives.
you can use reflections in c# to get all the properties of the dynamic object.
var nameOfProperty = "test";
var propertyInfo = game.GetType().GetProperty(nameOfProperty);
var value = propertyInfo.GetValue(game, null);
Moreover, you can simply use this way to get the value if you know the property name
string value = game["test"];

Why is my custom attribute parameters null?

Here is my code:
[AttributeUsage(AttributeTargets.Method)]
public class WorkAttribute : System.Attribute
{
public string Message;
public WorkAttribute(string message)
{
this.Message = message;
}
}
[Work("WorkMessage")]
public void test(){...}
foreach (MethodInfo methodInfo in type.GetMethods())// type is the class's type
{
WorkAttribute workAttribute = methodInfo.GetCustomAttribute<WorkAttribute>();
if (workAttribute != null)
{
Console.WriteLine(workAttribute.Message);// Should print "WorkMessage", but Message is null.
}
}
When I set a break point at the WorkAttribute's constructor, I can see the message past in correctly. But after I call GetCustomAttribute, all the fields inside WorkAttribute is null.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
[AttributeUsage(AttributeTargets.Method)]
public class WorkAttribute : System.Attribute
{
public string Message;
public WorkAttribute(string message)
{
this.Message = message;
}
}
class Program
{
[Work("WorkMessage")]
public void test()
{
}
static void Main()
{
foreach (MethodInfo methodInfo in typeof(Program).GetMethods())
{
WorkAttribute workAttribute = methodInfo.GetCustomAttribute<WorkAttribute>();
if (workAttribute != null)
{
Console.WriteLine(workAttribute.Message);// Should print "WorkMessage", but Message is null.
}
Console.ReadLine();
}
}
}
}
This code prints "WorkMessage" just fine. Compare your non-posted code. You may be using the wrong method or wrong type or set the Message somewhere else.

Inconsistent accessibility with protected internal member

Attempting to make a protected internal member of a protected internal class within a public class results with the following issue:
Inconsistent accessibility: field type
'what.Class1.ProtectedInternalClass' is less accessible than field
'what.Class1.SomeDataProvider.data'
The accessibility should be equivalent, as far as I know.
Where am I mistaken?
Origination class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace what
{
public class Class1
{
// This class cannot be modified, is only
// here to produce a complete example.
public class PublicClass
{
public PublicClass() { }
}
protected internal class ProtectedInternalClass : PublicClass
{
public ProtectedInternalClass() { }
public void SomeExtraFunction() { }
}
public class SomeDataProvider
{
public int AnInterestingValue;
public int AnotherInterestingValue;
protected internal ProtectedInternalClass data; //<--- Occurs here.
public PublicClass Data { get { return data; } }
}
public static SomeDataProvider RetrieveProvider()
{
SomeDataProvider provider = new SomeDataProvider();
provider.data = new ProtectedInternalClass();
provider.data.SomeExtraFunction();
return provider;
}
}
}
Verifying protected and internal properties, same assembly:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace what
{
public class Class2 : Class1
{
public Class2()
{
var pi = new ProtectedInternalClass();
var provider = new SomeDataProvider();
provider.data = pi;
}
// no errors here
}
public class Class3
{
public Class3()
{
var pi = new Class1.ProtectedInternalClass();
var provider = new Class1.SomeDataProvider();
provider.data = pi;
}
// no errors here
}
}
Verifying protected and internal properties, different assembly:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace some_other_assembly
{
public class Class4 : what.Class1
{
public Class4()
{
var pi = new ProtectedInternalClass();
var provider = new SomeDataProvider();
provider.data = pi;
}
// no errors here
}
public class Class5
{
public Class5()
{
var pi = new what.Class1.ProtectedInternalClass(); // <--- Inaccessible due to protection level, as it should be.
var provider = new what.Class1.SomeDataProvider();
provider.data = pi; // <--- Intellisense implies inaccessible, but not indicated via error.
}
}
}
The protected applies to different classes, and this can be seen with
class Derived : what.Class1.SomeDataProvider // note: Derived is not a nested class
{
public void f()
{
var data = this.data;
}
}
in a different assembly.
this.data has to be accessible, since the class derives from SomeDataProvider. Its type, ProtectedInternalClass, is not accessible, since the class does not derive from Class1.

Cast a class object to an interface object using reflection C#

There have two dll's namely
a) lib1
b) lib2
These two library are loaded using reflection( as against to adding a direct reference in visual studio). I'm creating an object of a class , then want to type cast that object to the type of the interface (interface being in the dll loaded in the main program). I get an error saying type mismatch. Any possible solution to this problem.
Here is my code block:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace Interfaceconversion
{
class Program
{
public static object classobj;
public static object interfaceobj;
static void Main(string[] args)
{
// Loading assembley 1
Assembly assembly1 = Assembly.LoadFrom(#"D:\WCFService\Aug9\Interfaceconversion\Lib1\bin\Debug\Lib1.dll");
Type[] type1 = assembly1.GetTypes();
foreach (Type item in type1)
{
if (item.FullName.ToString() == "Lib1.Class1")
{
classobj = Activator.CreateInstance(item);
}
}
// Loading assembly 2
Assembly assembly2 = Assembly.LoadFrom(#"D:\WCFService\Aug9\Interfaceconversion\Lib2\bin\Debug\Lib2.dll");
Type[] type2 = assembly2.GetTypes();
Type libtype = type2[1];
foreach (Type item in type2)
{
if (item.FullName.ToString() == "Lib2.Ilib2Interface1")
{
TODO: cast the object "classobj " to type Lib2.Ilib2Interface1
interfaceobj = classobj as item ;
}
}
#region old code
}
}
Lib2 dll's code is :
lib2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lib2
{
interface Ilib2Interface1
{
void lib2disp1();
}
}
Lib1 code is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lib1
{
interface ISttutil
{
void displayutil1();
void displayutil2();
}
interface Isttinterface
{
void displayinterface1();
void displayinterface2();
}
}
We don't see lib1.Class1 in the example given, but provided it derives from the interface you want to cast it to, something like this should work:
lib1:
using lib2;
using System;
namespace lib1
{
public class Class1 : IInterface1
{
public void MethodOne ( )
{
Console.WriteLine ( "MethodOne called!" );
}
}
}
lib2:
namespace lib2
{
public interface IInterface1
{
void MethodOne ( );
}
}
Main:
using lib2;
using System;
using System.IO;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void Main ( string [ ] args )
{
var fileInfo = new FileInfo ( #".\lib1.dll" );
var assembly = Assembly.LoadFile ( fileInfo.FullName );
var obj = assembly.CreateInstance ( "lib1.Class1" ) as IInterface1;
if ( obj != null ) obj.MethodOne ( );
Console.ReadLine ( );
}
}
}

Categories