I added .dll: AxWMPLib and using method get_Ctlcontrols() but it show error like:
AxWMPLib.AxWindowsMediaPlayer.Ctlcontrols.get': cannot explicitly call operator or accessor
This is my code using get_Ctlcontrols() method:
this.Media.get_Ctlcontrols().stop();
I don't know why this error appears. Can anyone explain me and how to resolve this problem?
It looks like you are trying to access a property by calling explicitly its get method.
Try this (notice that get_ and () are missing):
this.Media.Ctlcontrols.stop();
Here is a small example about how properties work in C# - just to make you understand, this does not pretend to be accurate, so please read something more serious than this :)
using System;
class Example {
int somePropertyValue;
// this is a property: these are actually two methods, but from your
// code you must access this like it was a variable
public int SomeProperty {
get { return somePropertyValue; }
set { somePropertyValue = value; }
}
}
class Program {
static void Main(string[] args) {
Example e = new Example();
// you access properties like this:
e.SomeProperty = 3; // this calls the set method
Console.WriteLine(e.SomeProperty); // this calls the get method
// you cannot access properties by calling directly the
// generated get_ and set_ methods like you were doing:
e.set_SomeProperty(3);
Console.WriteLine(e.get_SomeProperty());
}
}
Related
I have this code:
public class NewFrame
{
public NewFrame(string iconSource = Const.Car,
string iconColor = Const.Red)
{
When I try and use it then it's telling me I am missing a default constructor. How can I add one of these and still make the code use the default values for iconBackgroundColor and IconSource? I thought that adding in those defaults with the = Const. would make it work but it seems like it doesn't think my constructor is a default (with no params).
You just have to add another empty overload and call the required constructor with defaults. See below:
public class NewFrame
{
public NewFrame() : this(Const.Car, Const.Red){
}
public NewFrame(string iconSource,
string iconColor)
{
...
}
}
By having two optional parameters, you don't actually create 4 different constructor declarations under the hood (one with both parameters, one with the first parameter, one with the second parameter, and one with neither). There is still only one constructor, with two parameters. It's just that C# recognises that the parameters are optional, and has syntactic sugar to let you omit them when you call the constructor.
However, if you use reflection to create an instance of your class (probably whatever the thing that requires a default constructor is doing), and you attempt to invoke the parameterless constructor, it won't find one, because there is no syntactic sugar in reflection.
Here is an example:
class MainClass
{
public static void Main(string[] args)
{
Type t = typeof(MainClass);
object o = Activator.CreateInstance(t, 1);
Console.WriteLine(o);
}
public MainClass(int a = 10)
{
}
}
If you use typeof(MainClass).GetConstructors(), it will tell you that there is only one.
To actually declare a default constructor, you can do:
public class NewFrame
{
public NewFrame(string iconSource = Const.Car,
string iconColor = Const.Red)
{
...
}
public NewFrame() : this(Const.Car, Const.Red) { }
}
For what it's worth, when I do something like this, I take the route that #VyacheslavBenedichuk's answer is showing.
I'm not sure what your complaint is. This code compiles for me:
public class TestConstructor
{
public TestConstructor(string what = Const.Car, string color = Const.Red)
{
}
public static void Test()
{
var tc = new TestConstructor();
}
public class Const
{
public const string Car = "car";
public const string Red = "red";
}
}
What do your definitions of Const.Car and Const.Red look like? Where are you seeing the error?
But, if you use something that requires a default constructor, then this will not work. For example, this will fail at runtime:
var tc2 = Activator.CreateInstance(typeof(TestConstructor));
Please, when you are reporting an error, describe it exactly - in particular say whether it's a runtime or a compile-time error, the exact wording of the error, and the context in which the error occurs. In this case (the call to CreateInstance) will result in a System.MissingMethodException: 'No parameterless constructor defined for this object.'
In this case, you need to follow #VyacheslavBenedichuk's advice
I am using Moq to write test cases and when I try to assign the mock function within the constructor it comes up with the error saying that I cannot assign it because the target method is a group method however there is only one method defined.
I have written an interface etc. as follows:
...
public interface IRSPPortal
{
string GetOrderStatus(OrderInfo OrderNum);
}
public class RSPPortal : IRSPPortal
{
public RSPPortal(IRSPPortal GetOrderStatusMock)
{
this.GetOrderStatus = GetOrderStatusMock; //This line gives the error
}
public string GetOrderStatus(OrderInfo OrderNum)
{
//stuff done here to access a database
}
}
...
There is only one method GetOrderStatus(OrderInfo OrderNum) so I don't know why it has classified it as a method group. What is the simplest way to overcome this error?
I have tried to use
this.GetOrderStatus = GetOrderStatusMock.GetOrderStatus;
but that didn't work either.
Thanks everyone.
That's not how Moq works. If you want to mock IRSPPortal:
Mock<IRSPPortal> rspPortalMock = new Mock<IRSPPortal>();
rspPortalMock.Setup(a => a.GetOrderStatus(It.IsAny<OrderInfo>())).Returns(<string you want returned from the mocked method>);
Now you have a mock of IRSPPortal that will return whatever string you want from GetOrderStatus.
To use that mocked object just pass in rspPortalMock.Object to whatever class is using IRSPPortal.
given this delegate
public class XYZ
{
public static Action<Profile> DoSomething = (profile) =>
{
//some default code here
return;
};
}
at some time in my main execution I override it with this:
XYZ.DoSomething = (currProfile) =>
{
// some overriding code here
}
How do I set the code back to the original default code when I need to without duplicating code?
Here's a good reason to never use public fields...
Once you set it; its gone. You can hold onto the original value though:
var originalAction = XYZ.DoSomething;
XYZ.DoSomething = ...;
XYZ.DoSomething = originalAction;
Usually it is a bad idea to rely on client code to handle this however; so if I was writing it I would expose as a property like so:
public Action<X> DoSomethingOverride {get; set;}
public Action<X> DoSomething => doSomethingOverride ?? DefaultMethod;
private void DefaultMethod (X param)
{
}
There are a number of other ways to handle this, but all involve storing off the original method. All good ways to handle this will use a property to ensure that only the declaring class is actually setting the DoSomething method and that resetting to the default is possible.
Total aside; since this is static setting the action will affect everything that uses this class. This is asking for bugs later; don't do that.
Maybe somthing like this?
public static Action<Profile> _doSomethingBase = (profile) =>
{
//some default code here
return;
};
public static Action<Profile> _doSomething = _doSomethingBase;
public static Action<Profile> DoSomething
{
get => _doSomething;
set => _doSomething = value;
}
public static void RevertDoSomething()
{
DoSomething = _doSomethingBase;
}
Is there a way to do this:
var methodToDoStuffTo = typeof (FancyClass).GetMethod("MethodName").Name;
Without relaying on the string "MethodName"?
What I want is something like this:
var methodToDoStuffTo = typeof (FancyClass).GetMethod(FancyClass.MethodName).Name;
So I can be sure that there is no unexpected error when I rename my method MethodName.
For reasons I can't simple update my enviroment to c# 6, so no nameof().
I try and give a reason why I'am doing this:
I (have to) use one Authorization Attribute on several different Methods.
Depending on from which method the Attribute was 'called', the code has to do slitly different stuff.
That's why I can't / don't want to use differnet Attributes for each Method.
Depending on from which method the Attribute was 'called', the code has to do slitly different stuff
You should never do that. Letting magic stuff happen based on naming conventions is in most application code a bad idea that will lead to unexpected side-effects.
Just add a constructor parameter to the attribute:
public class YourAttribute : Attribute
{
private bool doSomethingDifferent;
public YourAttribute(bool doSomethingDifferent = false)
{
_doSomethingDifferent = doSomethingDifferent;
}
}
And apply it as such:
public class AttributeApplication
{
[YourAttribute]
public void NormalMethod()
{
}
[YourAttribute(doSomethingDifferent: true)]
public void MethodSomewhatDifferent()
{
}
}
But if you really want a type-safe GetMethod(), you could create an extension method with a MethodCallExpression, as explained in Get the name of a method using an expression.
The syntax will then become something like this:
var methodToDoStuffTo = typeof(FancyClass).GetMethod(c => c.MethodName()).Name;
But again, that approach should not be chosen lightly.
What code is generated by the C# compiler when I try to capture the parameter of a function?
partial class NewClass : Window
{
public NewClass()
{
InitializeComponent();
new Thread(Work).Start();
}
void Work()
{
Thread.Sleep(5000); // Simulate time-consuming task
UpdateMessage("The answer");
}
void UpdateMessage(string message)
{
Action action = () => txtMessage.Text = message;
Dispatcher.BeginInvoke(action);
}
}
I know lambdas can hold variables in their lexical scope after a new class is created - where said variables are stored as fields. The fields replace any original occurrence of captured ones. But in this case, since no original value is being replaced, will a value be created from scratch? What's the magic behind this?
So what's going on here is that you're not actually closing over txtMessage, technically. What you're doing is closing over this.
Every instance method has an implicit first parameter of the type of the class itself, called this. The access of any instance members assumes that they are accessing members of that implicitly defined this variable.
Once you make all of that implicit code explicit, it becomes just another closure over any other locally scoped variable.
So first we make this explicit: (This isn't technically valid C#, it is merely for demonstrative purposes and is designed to be a representation of the semantic representation of the code by the C# compiler.)
void UpdateMessage(NewClass this, string message)
{
Action action = () => this.txtMessage.Text = message;
Dispatcher.BeginInvoke(action);
}
Then we do the traditional closure transformations of a locally scoped variable on that:
class ClosureClass1
{
public string message;
public NewClass #this;
public void AnonymousMethod1()
{
#this.txtMessage.Text = message;
}
}
void UpdateMessage(NewClass this, string message)
{
ClosureClass1 closure = new ClosureClass1();
closure.#this = this;
closure.message = message;
Action action = closure.AnonymousMethod1;
Dispatcher.BeginInvoke(action);
}
The NewClass contains a created private field of type <>c__DisplayClass1 class which contains a public string field 'message'. Each time the UpdateMessage is called the method instantiates a new instance of the <>c__DisplayClass1 class and assigns the message passed into the UpdateMessage method (by value). It also contains the < UpdateMessage >b__0 which is the action to execute (assign textbox with the message value). The textbox value is set by using the 'this' field which is the MainWindow class.
Hope this answers your question!