我说的是属性PageSettings.PrinterResolution。根据MSDN,此属性具有一个setter,与属性PrinterResolution.X相同,即使我无法为其设置新的值。该属性仍包含其先前的值,而不是新分配的值。

PrintDocument pd = new PrintDocument();
//assigning a printer to `pd`, etc...

//premise: pd.DefaultPageSettings.PrinterResolution.X has currently the value 200


现在,我尝试为int分配一个新的X值:

pd.DefaultPageSettings.PrinterResolution.X = 300;


但是在检查后它的值pd.DefaultPageSettings.PrinterResolution.X仍然包含200。我只是想为新的PrinterResolution对象分配XYpd.DefaultPageSettings.PrinterResolution的设置值,以根据我的需要更改值。

PrinterResolution changedRes = new PrinterResolution();
changedRes.X = 200;
changedRes.Y = 200;

pd.DefaultPageSettings.PrinterResolution = changedRes;


那么,为什么不能设置属性的值?尤其是为什么即使没有“可用”,为什么也有记录在案的setter

最佳答案

如果查看PageSettingsreference source,您会发现总是从API重新请求PrinterResolution(只要您不手动设置PrinterResolution属性):

public PrinterResolution PrinterResolution {
    [ResourceExposure(ResourceScope.None)]
    [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
    get {
        if (printerResolution == null) {
            IntSecurity.AllPrintingAndUnmanagedCode.Assert();

            IntPtr modeHandle = printerSettings.GetHdevmode();
            IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(this, modeHandle));
            SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE) UnsafeNativeMethods.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));

            PrinterResolution result = PrinterResolutionFromMode(mode);

            SafeNativeMethods.GlobalUnlock(new HandleRef(this, modeHandle));
            SafeNativeMethods.GlobalFree(new HandleRef(this, modeHandle));

            return result;
        }
        else
            return printerResolution;
    }
    set {
        printerResolution = value;
    }
}


因此,只要您不手动设置PageSettings.PrinterResolution,每次访问PrinterResolution吸气剂时都会从API加载新的PageSettings.PrinterResolution实例。并且此新实例再次包含原始的X值。之前设置X的实例将被丢弃。

至于为什么我还不了解。

关于c# - 无法为属性分配新值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49409999/

10-11 22:40